[Python-ideas] Fwd: Anonymous namedtuples

Chris Angelico rosuav at gmail.com
Tue Apr 19 07:49:19 EDT 2016

On Tue, Apr 19, 2016 at 9:31 PM, Joseph Martinot-Lagarde
<contrebasse at gmail.com> wrote:
> Chris Angelico <rosuav at ...> writes:
>> On Tue, Apr 19, 2016 at 7:49 PM, Joseph Martinot-Lagarde
>> <contrebasse at ...> wrote:
>> > I'd be happy to make a factory function for my personal use, but the order
>> > of kwargs is not respected. To have an elegant syntax, it has to be a
>> > construct of the language.
>> There have been proposals to have kwargs retain some order (either by
>> having it actually be an OrderedDict, or by changing the native dict
>> type to retain order under fairly restricted circumstances). With
>> that, you could craft the factory function easily.
> I saw some proposals but forgot about them, thanks for the reminder.
> I'd prefer my proposal for two reasons:
> - the syntax is nicer that a factory function
> - it wouldn't be possible to add keyword arguments to __getitem__ without
> breaking compatibility
> Those issues are relatively minor, i'd be happy with a factory function

Agreed, the syntax is a lot nicer - for this specific situation. Don't
forget, though, that every piece of new syntax carries with it the not
insignificant cost of complexity; and some things are better
represented by function calls than syntax (cf 'print'). With "from
types import SimpleNamespace as NS" at the top of your code, you can
use the keyword-arguments form of the constructor to be almost the
same as your proposal, without any new syntax. When a subsequent
maintainer looks at your code, s/he can quickly look up at the imports
to see what's going on, instead of having to learn another piece of

> It's true that python already has some commodities in place. When I first
> heard about namedtuples I was pretty excited, but when I tried in practice
> they are not that easy to use, with lots of duplications (the name, and
> possibly the field names) and a global declaration.
> For all my use cases (not only function returns) I would completely replace
> namedtuple by anonymouns namedtuple.

I have to agree. Fortunately it isn't hard to create a namedtuple factory:

def NS(fields):
    return namedtuple('anonymous', fields.split())

or possibly:

def NS(fields, *values):
    return namedtuple('anonymous', fields.split())(*values)

That cuts down the duplication some, but it's far from perfect.


More information about the Python-ideas mailing list