[Python-il] Printing dictionary values rather than references

Tal Einat taleinat at gmail.com
Wed Jun 10 18:17:26 IDT 2009


Amit Dor-Shifer wrote:
> Hi all.
>
> I'd like to print-out a dictionary of objects. The printed values are
> references. How Do I print the actual objects.
>
> class MyClass:
>    def __str__(self):
>        return str(self.__dict__)
>
> if __name__ == '__main__':
>    dict = dict()
>    classA = MyClass()
>    setattr(classA, "attr-1", "val-1")
>
>    dict['a']= classA
>    print classA
>    ''' Desired output: {'attr-1': 'val-1'}'''
>    print dict
>    ''' Actual output: {'a': <__main__.MyClass instance at 0x79cfc8>}'''
>
> Thanks,
> Amit

Hi Amit,

You should add a __repr__ method to your class. This method is called
when you print an instance of the class; in the absence of a __repr__
method, the default representation is printed: <__main__.MyClass
instance at 0x...>

For example:
class MyClass:
    def __str__(self):
        return str(self.__dict__)
    def __repr__(self):
        return str(self)


The difference between the __str__ and __repr__ methods is that
__str__ is for conversion of an instance to a string, while __repr__
should return a human-readable representation of the instance, usually
used by developers for debugging etc. Sometimes these are the same but
not always, check out collections.defaultdict for an example.

For more information see:
http://docs.python.org/reference/datamodel.html#object.__repr__

- Tal


More information about the Python-il mailing list