Friday, April 29, 2011

Auto __repr__ method

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

From stackoverflow
  • Do you mean

    __dict__
    

    ?

  • 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.

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

0 comments:

Post a Comment