Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Metaclass to add __repr__
def general_repr(self):
'''Returns class's representation as string.
Example usage:
class Test(object):
__repr__ = general_repr
def __init__(self):
self.test = "Hello world"
t = Test()
print 'instance: %r' % t'''
return '%s(%s)' % (self.__class__.__name__, ', '.join('%s=%r' % item for item in self.__dict__.iteritems()))
class MetaRepr(type):
'''Metaclass to add general representation to any class.
If you want to apply this effect globally, just define
global __metaclass__ like this:
__metaclass__ = MetaRepr'''
def __init__(cls, name, bases, dict):
super(MetaRepr, cls).__init__(name, bases, dict)
setattr(cls, '__repr__', general_repr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment