Say I want to debug a simple class with an attribute myattribute
. I create a repr
method like this:
class SimpleClass:
def __repr__(self):
return "{0.myattribute}".format(self)
It feels a bit redundant, so I would prefer to use format
directly:
class SimpleClass:
__repr__ = "{0.myattribute}".format
...but that fails with an IndexError: tuple index out of range
. I understand it that format
cannot access the self
argument, but I do not see why.
Am I doing something wrong, is this a CPython limitation – or what else?
"{0.myattribute}".format
is already a bound method on the string object ("{0.myattribute}"
). So when the calling code attempts to look up, say, x.__repr__
(where x
is a SimpleClass
instance), Python finds the __repr__
attribute of SimpleClass
, but then cannot recognize it as a SimpleClass
method - the descriptor protocol is not honoured (the string method has no __get__
attribute).
It appears that in 3.4, using a lambda
will work, although I could have sworn it had to be a real function in previous versions. functools.partial
will not work. But you really should be using a real function anyway. Sorry it's not as DRY as you'd like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With