On 1 October 2012 13:16, Albert-Jan Roskam <fo...@yahoo.com> wrote:
>
>> On Sat, Sep 29, 2012 at 4:15 PM, Albert-Jan Roskam <fo...@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
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to