Paste number 153363: generic object printer

Index of paste annotations: 1

Paste number 153363: generic object printer
Pasted by: phf
When:6 years, 11 months ago
Share:Tweet this! | http://paste.lisp.org/+3AC3
Channel:None
Paste contents:
Raw Source | XML | Display As
(defmethod print-object ((object standard-object) stream)
  (print-unreadable-object (object stream :type t :identity t)
    (let ((slot-names #+ccl (mapcar #'ccl:slot-definition-name (ccl:class-slots (class-of object)))
                      #+sbcl (mapcar #'sb-pcl:slot-definition-name (sb-pcl:class-slots (class-of object)))))
      (format stream "~{~a~^ ~}" 
              (mapcar (lambda (slot)
                        (if (slot-boundp object slot)
                            (cons slot (slot-value object slot))
                            slot))
                      slot-names)))))

Annotations for this paste:

Annotation number 1: example
Pasted by: phf
When:6 years, 11 months ago
Share:Tweet this! | http://paste.lisp.org/+3AC3/1
Paste contents:
Raw Source | Display As
? (defclass foo () ((a :initarg :a) (b :initarg :b)))
#<STANDARD-CLASS FOO>
? (make-instance 'foo :a 123 :b "abc")
#<FOO #x302000DD8BBD>
? (defun get-foo () (make-instance 'foo :a 123 :b "abc"))
GET-FOO
? (get-foo)
#<FOO #x302000DD8BED>
? (defmethod print-object ((object standard-object) stream)
    (print-unreadable-object (object stream :type t :identity t)
      (let ((slot-names #+ccl (mapcar #'ccl:slot-definition-name (ccl:class-slots (class-of object)))
                        #+sbcl (mapcar #'sb-pcl:slot-definition-name (sb-pcl:class-slots (class-of object)))))
        (format stream "~{~s~^ ~}" 
                (mapcar (lambda (slot)
                          (if (slot-boundp object slot)
                              (cons slot (slot-value object slot))
                              slot))
                        slot-names)))))
#<STANDARD-METHOD PRINT-OBJECT (STANDARD-OBJECT T)>
? (get-foo)
#<FOO (A . 123) (B . "abc") #x302000E2EEDD>

Colorize as:
Show Line Numbers

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.