[Tutor] generic repr method?

eryksun eryksun at gmail.com
Sun Sep 30 01:46:56 CEST 2012


On Sat, Sep 29, 2012 at 4:15 PM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
>     def __repr__(self):
>         code = self.__class__.__name__ + "("
>         for arg in inspect.getargspec(self.__init__).args [1:]  :
>             if isinstance(eval("self." + arg), basestring):
>                 code += ("%(" + arg + ")r, ")
>             else:
>                 code += ("%(" + arg + ")s, ")
>         code = code[:-2] + ")"
>         return code % self.__dict__


__init__ could use *args and **kwds.
Keyword-only arguments in Python 3 require using inspect.getfullargspec.
A class with __slots__ probably lacks a __dict__.
Use the repr of all values.

The current value of an attribute isn't necessarily the value needed
for initialization, nor do all initialization arguments necessarily
map to attributes. So you can't expect a general-purpose __repr__ to
capture everything that's needed to recreate the object. It's nice to
try for this, but not necessary. It is important, however, to include
information relevant for debugging:

http://docs.python.org/py3k/reference/datamodel.html#object.__repr__

Also see:

http://docs.python.org/py3k/library/copy
http://docs.python.org/py3k/library/pickle.html#pickling-class-instances


More information about the Tutor mailing list