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

John Wong gokoproject at gmail.com
Sun Sep 14 20:48:04 CEST 2014


Hi,

>>> from collections import namedtuple
>>> A  = namedtuple("A", ["foo"])
>>> print(A(foo=1))
A(foo=1)
>>> str(A(foo=1))
'A(foo=1)'
>>> repr(A(foo=1))
'A(foo=1)'

The relevant code is
https://hg.python.org/cpython/file/2.7/Lib/collections.py#l356

I propose we bring the behavior to regular classes.

Instead of

>>> 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)'

Reasons:

1. Helps debugging (via pdb, print and logging). We no longer have to do
A().foo to find out.
2. I don't know how often people actually rely on repr(A()) or str(A()) and
parse the string so breaking compatibility is, probably low.
3. People who wish to define their own repr and str is welcome. Django
model for example has a more explicit representation by default (although
many Django users do redefine the representation on their own).
datetime.datetime by default, as a library, is also explicit. So
customization will come.

The main challenge:

Where and how do we actually look for what attributes are relevant?
namedtuple can do it because it has __slot__ and we know in advance how
many attributes are set. In regular class, we deal with dynamic attribute
setting, single and inheritances. I don't have an answer for this simply
because I lack of experience. We can certainly start with the attributes
set in the main instance and one level up in the inheritance chain.

Other issues:
1. What if there are too many attributes? I don't think the number will
explode beyond 30. I choose this number out of thin air. I can do more
research on this. It doesn't actually hurt to see everything. If you do
have a class with so many attribute (whether you have this many to begin
with, or because you allow aritbary numbers of attributes to be set -- for
example, a document from a collection in NoSQL like MongoDB), that's still
very useful. We could limit by default up to how many.

2. How do we order them? We can order them in unsorted or sorted order. I
prefer the sorted order.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140914/2b627985/attachment.html>


More information about the Python-ideas mailing list