Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use `str.format` directly as `__repr__`?

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?

like image 821
emu Avatar asked Oct 31 '22 15:10

emu


1 Answers

"{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.

like image 95
Karl Knechtel Avatar answered Nov 16 '22 15:11

Karl Knechtel