[Python-ideas] namedtuple literals [Was: RE a new namedtuple]

Nick Coghlan ncoghlan at gmail.com
Wed Jul 26 12:05:47 EDT 2017


On 26 July 2017 at 11:05, Steven D'Aprano <steve at pearwood.info> wrote:
> I don't see any way that this proposal can be anything by a subtle
> source of bugs. We have two *incompatible* requirements:
>
> - we want to define the order of the fields according to the
>   order we give keyword arguments;
>
> - we want to give keyword arguments in any order without
>   caring about the field order.
>
> We can't have both, and we can't give up either without being a
> surprising source of annoyance and bugs.

I think the second stated requirement isn't a genuine requirement, as
that *isn't* a general expectation.

After all, one of the reasons we got ordered-by-default keyword
arguments is because people were confused by the fact that you
couldn't reliably do:

    mydict = collections.OrderedDict(x=1, y=2)

Now, though, that's fully supported and does exactly what you'd expect:

    >>> from collections import OrderedDict
    >>> OrderedDict(x=1, y=2)
    OrderedDict([('x', 1), ('y', 2)])
    >>> OrderedDict(y=2, x=1)
    OrderedDict([('y', 2), ('x', 1)])

In this case, the "order matters" expectation is informed by the
nature of the constructor being called: it's an *ordered* dict, so the
constructor argument order matters.

The same applies to the ntuple concept, expect there it's the fact
that it's a *tuple* that conveys the "order matters" expectation.

    ntuple(x=1, y=2) == ntuple(y=1, x=2) == tuple(1, 2)
    ntuple(x=2, y=1) == ntuple(y=2, x=1) == tuple(2, 1)

Putting the y-coordinate first would be *weird* though, and I don't
think it's an accident that we mainly discuss tuples with strong order
conventions in the context of implicit typing: they're the ones where
it feels most annoying to have to separately define that order rather
than being able to just use it directly.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list