[Python-ideas] Fwd: Anonymous namedtuples
Peter Otten
__peter__ at web.de
Tue Apr 19 13:55:59 EDT 2016
Guido van Rossum wrote:
> A general warning about this (x=12, y=16) idea: It's not so different from
> using dicts as cheap structs, constructing objects on the fly using either
> {'x': 12, 'y': 16} or dict(x=12, y=16). The problem with all these this is
> that if you use this idiom a lot, you're invariably going to run into
> cases where a field is missing, and you're spending a lot of time tracking
> down where the object was created incorrectly. Using a namedtuple (or any
> other construct that asks you to pre-declare the type used) the incorrect
> construction will cause a failure right at the point where it's being
> incorrectly constructed, making it much simpler to diagnose.
>
> In fully typed languages like Haskell or Java this wouldn't be a problem,
> but in languages like Python or Perl it is a real concern.
If there were support from the compiler for a function
def f():
return x=1, y=2
the namedtuple("_", "x y") class could be stored in f.__code__.co_consts
just like 1 and 2. Adding information about the file and line number could
probably be handled like it's done for code objects of classes and functions
defined inside a function.
While this approach still produces "late" failures debugging should at least
be easier than for dict or SimpleNamespace instances.
More information about the Python-ideas
mailing list