Can I define a __repr__ for a class rather than an instance?
Sure, I demonstrate here, with a __repr__
that passes the repr
test.
class Type(type):
def __repr__(cls):
"""
>>> Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
"""
name = cls.__name__
parents = ', '.join(b.__name__ for b in cls.__bases__)
if parents:
parents += ','
namespace = ', '.join(': '.join(
(repr(k), repr(v) if not isinstance(v, type) else v.__name__))
for k, v in cls.__dict__.items())
return 'Type(\'{0}\', ({1}), {{{2}}})'.format(name, parents, namespace)
def __eq__(cls, other):
return (cls.__name__, cls.__bases__, cls.__dict__) == (
other.__name__, other.__bases__, other.__dict__)
And to demonstrate:
class Foo(object): pass
class Bar(object): pass
Either Python 2:
class Baz(Foo, Bar):
__metaclass__ = Type
Or Python 3:
class Baz(Foo, Bar, metaclass=Type):
pass
Or fairly universally:
Baz = Type('Baz', (Foo, Bar), {})
>>> Baz
Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
And to do the repr
test:
def main():
print Baz
assert Baz == eval(repr(Baz))
What is the repr
test? It's the above test from the documentation on repr
:
>>> help(repr)
Help on built-in function repr in module __builtin__:
repr(...)
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.