[Python-ideas] Bring namedtuple's __str__ and __repr__ behavior to regular classes

Chris Angelico rosuav at gmail.com
Sun Sep 14 21:00:24 CEST 2014


On Mon, Sep 15, 2014 at 4:48 AM, John Wong <gokoproject at gmail.com> wrote:
>>>> class A(object):
> ...     def __init__(self):
> ...             self.foo = 1
> ...
>>>> repr(A())
> '<__main__.A object at 0x1090c0990>'
>
>
> We should be able to see the current values to the display.
>>>> repr(A())
> 'A(foo=1)'

Start with this:

class object(object):
    def __repr__(self):
        return whatever_you_want_to_do

Then whenever you subclass object in this module, you'll subclass your
own subclass of object, and get your own repr. That's something that
will work on all versions of Python, including 2.x which isn't going
to get any changes like this. It's perfectly safe - it can't break
anyone's code but your own - and if you stick that at the top of the
file (or in another file and "from utils import object"), you don't
have to change anything else, assuming you're explicitly subclassing
object everywhere.

ChrisA


More information about the Python-ideas mailing list