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

Stephen J. Turnbull turnbull.stephen.fw at u.tsukuba.ac.jp
Thu Jul 27 21:24:09 EDT 2017


Ethan Furman writes:

 > Tuples, named or otherwise, are positional first -- order matters.
 > Specifying
 > 
 >      point = ntuple(y=2, x=-3)
 > 
 > and having point[0] == 3 is going to be bizarre.  This will be a
 > source for horrible bugs.

I don't see how you get that?

Anyway, I expect that ntuples will *very* frequently be *written* in an
order-dependent (and probably highly idiomatic) way, and *read* using
attribute notation:

    def db_from_csv(sheet):
        db = []
        names = next(sheet)
        for row in sheet:
            db.append(ntuple(**zip(names, row)))
        return db

    my_db = []
    for sheet in my_sheets:
        my_db.extend(db_from_csv(sheet))
    x_index = my_db[:].sort(key=lambda row: row.x)
    y_index = my_db[:].sort(key=lambda row: row.y)

(untested).  As far as I can see, this is just duck-typed collection
data, as Chris Barker puts it.  Note that the above idiom can create a
non-rectangular database from sheets of arbitrary column orders as
long as both 'x' and 'y' columns are present in all of my sheets.  A
bit hacky, but it's the kind of thing you might do in a one-off
script, or when you're aggregating data collected by unreliable RAs.

Sure, this can be abused, but an accidental pitfall?  Seems to me just
as likely that you'd get that with ordinary tuples.  I can easily
imagine scenarios like "Oh, these are tuples but I need even *more*
performance.  I know!  I'll read my_db into a numpy array!"  But I
would consider that an abuse, or at least a hack (consider how you'd
go about getting variable names for the numpy array columns).


More information about the Python-ideas mailing list