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

Chris Barker chris.barker at noaa.gov
Mon Jul 24 21:15:12 EDT 2017


On Fri, Jul 21, 2017 at 8:18 AM, Guido van Rossum <guido at python.org> wrote:

> Honestly I would like to declare the bare (x=1, y=0) proposal dead. Let's
> encourage the use of objects rather than tuples (named or otherwise) for
> most data exchanges. I know of a large codebase that uses dicts instead of
> objects, and it's a mess. I expect the bare ntuple to encourage the same
> chaos.
>

I've seen the same sort of mess, but I think it's because folks have come
down on the wrong side of "what's code, and what's data?"

Data belongs in dicts (and tuples, and lists, and...) and code belongs in
objects.

With Python's dynamic nature, it is very easy to blur these lines, but the
way I define it:

a_point['x']

is accessing data, and

a_point.x

is running code. It more or less comes down to -- "if you know the names
you need when you are writing the code, then it is probably code. So be
wary if you are using literals for dict keys frequently.

But from this perspective a NamedTuple (with or without a clearly defined
type) is code, as it should be.

In the duck-typing spirit, you should be able to do something like:

p = get_the_point(something)

do_something_with(p.x, p.y)

And not know or care what type p is.

With this perspective, a NamedTuple, with a known type or otherwise, AVOIDS
the chaos of passing dicts around, and thus should be encouraged.

And indeed, making it as easy as possible to create and pass an
object_with_attributes around, rather than a plain tuple or dict would be a
good thing.

I do agree that we have multiple goals on the table, and DON'T want to have
any more similar, but slightly different, lightweight objects with named
attributes.

So it makes sense to:

1) make namedtuple faster

and then, optionally:

2) make it easier to quickly whip out an (anonymous) namedtuple.

Maybe types.SimpleNamespace is the "better" solution to the above, but it
hasn't gained the traction that namedtuple has. And there is a lot to be
said for imutablilty, and the SimpleNamespace docs even say: "...  for a
structured record type use namedtuple()
<https://docs.python.org/3/library/collections.html#collections.namedtuple>
instead."

-CHB


-- 

Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170724/e9cfe1e6/attachment.html>


More information about the Python-ideas mailing list