tags:

views:

117

answers:

2

I want to have simple representation of any class, like { property = value }, is there auto __repr__?

+3  A: 

Do you mean

__dict__

?

uzi
+2  A: 

Yes, you can make a class "AutoRepr" and let all other classes extend it:

>>> class AutoRepr(object):
...     def __repr__(self):
...         items = ("%s = %r" % (k, v) for k, v in self.__dict__.items())
...         return "<%s: {%s}>" % (self.__class__.__name__, ', '.join(items))
... 
>>> class AnyOtherClass(AutoRepr):
...     def __init__(self):
...         self.foo = 'foo'
...         self.bar = 'bar'
...
>>> repr(AnyOtherClass())
"<AnyOtherClass: {foo = 'foo', bar = 'bar'}>"

Note that the above code will not act nicely on data structures that (either directly or indirectly) reference themselves. As an alternative, you can define a function that works on any type:

>>> def autoRepr(obj):
...     try:
...         items = ("%s = %r" % (k, v) for k, v in obj.__dict__.items())
...         return "<%s: {%s}." % (obj.__class__.__name__, ', '.join(items))
...     except AttributeError:
...         return repr(obj)
... 
>>> class AnyOtherClass(object):
...     def __init__(self):
...         self.foo = 'foo'
...         self.bar = 'bar'
...
>>> autoRepr(AnyOtherClass())
"<AnyOtherClass: {foo = 'foo', bar = 'bar'}>"
>>> autoRepr(7)
'7'
>>> autoRepr(None)
'None'

Note that the above function is not defined recursively, on purpose, for the reason mentioned earlier.

Stephan202
__dict__ is not showing class AnyOtherClass(object): foo = 'hello'
dynback.com