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

Terry Reedy tjreedy at udel.edu
Mon Sep 15 03:03:13 CEST 2014


On 9/14/2014 3:08 PM, Chris Angelico wrote:
> By the way:
>
> On Mon, Sep 15, 2014 at 4:48 AM, John Wong <gokoproject at gmail.com> wrote:
>> 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.
>
> This is a fundamentally hard problem. Obviously it's easy to see what
> attributes are set, but figuring out which are relevant is usually a
> job for the class itself.

There is also the problem that the representation of even one value can 
be arbitrarily long.  Named tuples, as used in the stdlib, usually have 
a relatively small number of fields with values with (currently) short 
representations.  That is not so in general.

A third problem is that the change would apply recursively.  If a named 
tuple now has an <io.BufferedText object at 0xnnnnnnnn> member, the 
representation of that would expand greatly, and so would the 
named-tuple representation and that of anything that contains a named tuple.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list