Differences creating tuples and collections.namedtuples

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Feb 18 20:43:12 EST 2013


On 19 February 2013 00:18, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Terry Reedy wrote:
>> On 2/18/2013 6:47 AM, John Reid wrote:
[snip]
>>> Is this a problem with namedtuples, ipython or just a feature?
>>
>> With canSequence. If isinstance was available and the above were written
>> before list and tuple could be subclassed, canSequence was sensible when
>> written. But as Oscar said, it is now a mistake for canSequence to
>> assume that all subclasses of list and tuple have the same
>> initialization api.
>
> No, it is not a mistake. It is a problem with namedtuples that they violate
> the expectation that they should have the same constructor signature as
> other tuples. After all, namedtuples *are* tuples, they should be
> constructed the same way. But they aren't, so that violates a reasonable
> expectation.

It is a mistake. A namedtuple class instance provides all of the
methods/operators provided by a tuple. This should be sufficient to
fill the tuplishness contract. Requiring that obj satisfy a contract
is one thing. When you get to the point of requiring that type(obj)
must do so as well you have gone beyond duck-typing and the normal
bounds of poly-morphism.

It's still unclear what the purpose of canSequence is, but I doubt
that there isn't a better way that it (and its related functions)
could be implemented that would not have this kind of problem.


Oscar



More information about the Python-list mailing list