[Python-ideas] automation of __repr__/__str__ for all the common simple cases

Steven D'Aprano steve at pearwood.info
Thu Feb 16 00:43:33 CET 2012


Ronny Pfannschmidt wrote:
> Hi,
> 
> in my experience for many cases, __repr__ and __str__ can be 
> unconditionally be represented as simple string formatting operation,

In my experience, not so much.


> so i would propose to add a extension to support simply declaring them 
> in the form of newstyle format strings

Declare them how? What is your proposed API for using this new functionality? 
Before proposing an implementation, you should propose an interface.


> a basic implementation for __repr__ could look like:
> 
>  class SelfFormatter(string.Formatter):
>         def __init__(self, obj):
>             self.__obj = obj
>             string.Formatter.__init__(self)
> 
>         def get_value(self, key, args, kwargs):
>             if isinstance(key, str) and hasattr(self.__obj, key):
>                 return getattr(self.__obj, key)
>             return Formatter.get_value(self, key, args, kwargs)
> 
>   class SimpleReprMixing(object):
>     _repr_ = '<{__class__.__name__} at 0x{__id__!x}>'
>     def __repr__(self):
>         formatter = SelfFormatter(self)
>         return formatter.vformat(self._repr_, (), {'__id__':id(self)})


I don't think you need this just to get a generic "instance at id" string. If 
you inherit from object (and remember that all classes inherit from object in 
Python 3) you get this for free:

 >>> class K(object):
...     pass
...
 >>> k = K()
 >>> str(k)
'<__main__.K object at 0xb746068c>'



-- 
Steven




More information about the Python-ideas mailing list