[Python-ideas] namedtuple literals [Was: RE a new namedtuple]
levkivskyi at gmail.com
Thu Jul 20 08:56:29 EDT 2017
Something probably not directly related, but since we started to talk about
I think what would be great to eventually have is some form of pattern
Essentially pattern matching could be just a "tagged" unpacking protocol.
For example, something like this will simplify a common pattern
with a sequence of if isinstance() branches:
def func(arg: Union[Single, Pair]) -> int:
Single as a:
return a + 2
Pair as a, b:
return a * b
The idea is that the expression before ``as`` is evaluated, then if ``arg``
is an instance of the result,
then ``__unpack__`` is called on it. Then the resulting tuple is unpacked
into the names a, b, etc.
I think named tuples could provide the __unpack__, and especially it would
be great for dataclasses
to provide the __unpack__ method. (Maybe we can then call it __data__?)
On 20 July 2017 at 11:39, Clément Pit-Claudel <cpitclaudel at gmail.com> wrote:
> On 2017-07-20 11:30, Paul Moore wrote:
> > On 20 July 2017 at 10:15, Clément Pit-Claudel <cpitclaudel at gmail.com>
> >> On 2017-07-20 11:02, Paul Moore wrote:
> >>>> Also, what's the advantage of (x=1, y=2) over ntuple(x=1, y=2)? I.e.,
> >>>> why does this need to be syntax instead of a library?
> >>> Agreed. Now that keyword argument dictionaries retain their order,
> >>> there's no need for new syntax here. In fact, that's one of the key
> >>> motivating reasons for the feature.
> >> Isn't there a speed aspect? That is, doesn't the library approach
> require creating (and likely discarding) a dictionary every time a new
> ntuple is created? The syntax approach wouldn't need to do that.
> > I don't think anyone has suggested that the instance creation time
> > penalty for namedtuple is the issue (it's the initial creation of the
> > class that affects interpreter startup time), so it's not clear that
> > we need to optimise that (at this stage)
> Indeed, it's not clear we do. I was just offering a response to the
> original question, "what's the advantage of (x=1, y=2) over ntuple(x=1,
> Python-ideas mailing list
> Python-ideas at python.org
> Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas