[Tutor] generic repr method?
Oscar Benjamin
oscar.j.benjamin at gmail.com
Mon Oct 1 16:24:11 CEST 2012
On 1 October 2012 13:16, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
>> 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):
Please don't use eval for this. Python has a much better function that is
explicitly designed to use what you want., e.g.:
eval("self." + arg) # Bad
getattr(self, arg) # Good
>>> code += ("%(" + arg + ")r, ")
>>> else:
>>> code += ("%(" + arg + ")s, ")
>>> code = code[:-2] + ")"
>>> return code % self.__dict__
>>
> It seems that for my current project I could still use the code, though
I'd find it more readable if the keywords are also included in the string.
Is it so hard to write a repr for each class that needs one (most don't)?
I think most repr functions I've written have been very short and easy to
write.
def __repr__(self):
return 'MyClass(x={0}, y={1})'.format(self.x, self.y)
It's also good to think about each individual class and whether or not the
repr really makes sense.
Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20121001/c899cee3/attachment.html>
More information about the Tutor
mailing list