Skip to content Skip to sidebar Skip to footer

Python Repr For Classes

As the Python 2 documentation on __repr__ states: If at all possible, this (i.e. __repr__) should look like a valid Python expression that could be used to recreate an object wit

Solution 1:

Consider a slightly more complicated class:

classB(object):def__init__(self):
        self.foo=3

repr would need to return something like

type("B", (object,), { "__init__": lambda self: setattr(self, "foo", 3) })

Notice one difficulty already: not all functions defined by the def statement can be translated into a single lambda expression. Change B slightly:

classB(object):
    def__init__(self, x=2, y, **kwargs):
        print"in B.__init__"

How do you write an expression that defines B.__init__? You can't use

lambda self: print"in B.__init__"

because lambda expressions cannot contain statements. For this simple class, it is already impossible to write a single expression that defines the class completely.

Solution 2:

Because the default __repr__cannot know what statements were used to create the class.

The documentation you quote starts with If at all possible. Since it is not possible to represent custom classes in a way that lets you recreate them, a different format is used, which follows the default for all things not easily recreated.

If repr(A) were to just return 'A', that'd be meaningless. You are not recreating A, you'd just be referencing it then. "type('A', (object,), {})" would be closer to reflecting the class constructor, but that'd be a) confusing for people not familiar with the fact python classes are instances of type and b) never able to reflect methods and attributes accurately.

Compare the output to that of repr(type) or repr(int) instead, these follow the same pattern.

Solution 3:

I know this is an older question, but I found a way to do it.

The only way I know to do this is with a metaclass like so:

classA(object):
    secret = 'a'class_metaA(type):
        @classmethoddef__repr__(cls):
            return"<Repr for A: secret:{}>".format(A.secret)
    __metaclass__ =_metaA

outputs:

>>> A
<Repr for A: secret:a>

Solution 4:

Since neither "<class 'A'>" nor "A" can be used to re-create the class when its definition is not available, I think the question is moot.

Post a Comment for "Python Repr For Classes"