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

Let's say I want to debug a simple class with the myattribute attribute. I create a repr method as follows:

 class SimpleClass: def __repr__(self): return "{0.myattribute}".format(self) 

It feels a little redundant, so I would rather use format directly:

 class SimpleClass: __repr__ = "{0.myattribute}".format 

... but this does not work with IndexError: tuple index out of range . I understand that format cannot access the self argument, but I don't understand why.

Am I doing something wrong, is this a limitation of CPython - or what else?

+5
source share
1 answer

"{0.myattribute}".format already a related method for the string object ( "{0.myattribute}" ). Therefore, when the calling code tries to find up, say, x.__repr__ (where x is an instance of SimpleClass ), Python finds the __repr__ SimpleClass attribute, but then cannot recognize it as the SimpleClass method - the handle protocol is not executed (the string method does not have the __get__ attribute) .

It seems that in 3.4, using lambda will work, although I could swear that in previous versions it was a real feature. functools.partial will not work. But you should still use a real function. Sorry, this is not as dry as you would like.

+2
source

Source: https://habr.com/ru/post/1204715/


All Articles