Differences creating tuples and collections.namedtuples

John Reid j.reid at mail.cryst.bbk.ac.uk
Tue Feb 19 10:30:36 CET 2013



On 19/02/13 00:18, Steven D'Aprano wrote:
> Terry Reedy wrote:
> 
>> On 2/18/2013 6:47 AM, John Reid wrote:
>>
>>> I was hoping namedtuples could be used as replacements for tuples
>>  >  in all instances.
>>
>> This is a mistake in the following two senses. First, tuple is a class
>> with instances while namedtuple is a class factory that produces
>> classes. (One could think of namedtuple as a metaclass, but it was not
>> implemented that way.) 
> 
> 
> I think you have misunderstood. I don't believe that John wants to use the
> namedtuple factory instead of tuple. He wants to use a namedtuple type
> instead of tuple.
> 
> That is, given:
> 
> Point3D = namedtuple('Point3D', 'x y z')
> 
> he wants to use a Point3D instead of a tuple. Since:
> 
> issubclass(Point3D, tuple) 
> 
> holds true, the Liskov Substitution Principle (LSP) tells us that anything
> that is true for a tuple should also be true for a Point3D. That is, given
> that instance x might be either a builtin tuple or a Point3D, all of the
> following hold:
> 
> - isinstance(x, tuple) returns True
> - len(x) returns the length of x
> - hash(x) returns the hash of x
> - x[i] returns item i of x, or raises IndexError
> - del x[i] raises TypeError
> - x + a_tuple returns a new tuple
> - x.count(y) returns the number of items equal to y
> 
> etc. Basically, any code expecting a tuple should continue to work if you
> pass it a Point3D instead (or any other namedtuple).
> 
> There is one conspicuous exception to this: the constructor:
> 
> type(x)(args)
> 
> behaves differently depending on whether x is a builtin tuple, or a Point3D.
> 

Exactly and thank you Steven for explaining it much more clearly.




More information about the Python-list mailing list