[Python-ideas] namedtuple literals [Was: RE a new namedtuple]
ncoghlan at gmail.com
Thu Jul 27 07:19:07 EDT 2017
On 27 July 2017 at 03:10, Steven D'Aprano <steve at pearwood.info> wrote:
> On Thu, Jul 27, 2017 at 02:05:47AM +1000, Nick Coghlan wrote:
>> 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)
> Indeed. But the reason we got *keyword arguments* in the first place was
> so you didn't need to care about the order of parameters. As is often
> the case, toy examples with arguments x and y don't really demonstrate
> the problem in real code. We need more realistic, non-trivial examples.
Trivial examples in ad hoc throwaway scripts, analysis notebooks, and
student exercises *are* the use case.
For non-trivial applications and non-trivial data structures with more
than a few fields, the additional overhead of predefining and
appropriately documenting a suitable class (whether with
collections.namedtuple, a data class library like attrs, or completely
by hand) is going to be small relative to the overall complexity of
the application, so the most sensible course of action is usually
going to be to just go ahead and do that.
Instead, as Alexandre describes, the use cases that the ntuple builtin
proposal aims to address *aren't* those where folks are already
willing to use a properly named tuple: it's those where they're
currently creating a *plain* tuple, and we want to significantly lower
the barrier to making such objects a bit more self-describing, by
deliberately eliminating the need to predefine the related type. In an
educational setting, it may even provide a gentler introduction to the
notion of custom class definitions for developers just starting out.
>From an API user's perspective, if you see `ntuple(x=1, y=2)` as an
object's representation, that will also carry significantly more
concrete information about the object's expected behaviour than if you
see `Point2D(x=1, y=2)`.
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas