[Tutor] generic repr method?

Oscar Benjamin oscar.j.benjamin at gmail.com
Sun Sep 30 01:16:48 CEST 2012


On 29 September 2012 21:15, Albert-Jan Roskam <fomcl at yahoo.com> wrote:

> Hi,
>
> I've written a __repr__ method that is supposed to *always* work. That is,
> it returns an eval-able text representation of any class instance.
> Will this really always work?


No.


> I'd find it useful is this is standard behavior of Python. Or am I
> overlooking something?
>

Yes.


>
>
> import inspect
>
> class X (object):
>
>     def __init__(self, x=1, y='n'):
>         self.x = x
>         self.y = y
>
>     def __repr__(self):
>         code = self.__class__.__name__ + "("
>         for arg in inspect.getargspec(self.__init__).args [1:]  :
>             if isinstance(eval("self." + arg), basestring):
>

I'd prefer getattr(self, arg) to eval("self." + arg).


>                 code += ("%(" + arg + ")r, ")
>             else:
>                 code += ("%(" + arg + ")s, ")
>         code = code[:-2] + ")"
>         return code % self.__dict__
>
> x = X()
> eval(repr(x))
>

This repr method assumes that every argument to __init__ is stored as an
attribute with the same name as the parameter to __init__. Consider:

def __init__(self, name):
    self.other_name = name

Also how do you handle:

def __init__(self, *args, **kwargs):

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120930/73810c19/attachment-0001.html>


More information about the Tutor mailing list