[Python-ideas] namedtuple baseclass
Steven D'Aprano
steve at pearwood.info
Sun Jan 12 12:55:16 CET 2014
On Sun, Jan 12, 2014 at 10:46:51PM +1100, Chris Angelico wrote:
> On Sun, Jan 12, 2014 at 10:43 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> > It's a tuple. It already uses __getitem__ to return items indexed by
> > position. Adding magic so that obj["fields"] is an alias for
> > obj._fields is, well, horrible.
>
> It's only an alias in the simple version that I did there. If it were
> to be used as a means of avoiding the _fields reserved name, it
> wouldn't be an alias. But yes, it is somewhat magical. I was hunting
> for an out-of-band way to get that sort of information.
I still don't get how you think this solves the problem that the OP's
use-case is to use isinstance() to identify namedtuples, then read
_fields. But with the (proposed, not implemented) namedtuple ABC,
isinstance(o, NamedTuple) could be true and o._fields fail. Breaking
backwards compatibility to write that as o["fields"] instead won't help,
because it will still fail:
py> t = os.stat_result([1]*10)
py> t["fields"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: tuple indices must be integers, not str
Changing namedtuple is not enough.
Oh, and this is a backwards-compatibility breaking change, because
_fields is part of the *public* API for namedtuple, despite the leading
underscore.
So I fail to see how anything short of a massive re-engineering of not
just namedtuple but also any C namedtuple-like types will satisfy the
OP's use-case. Have I missed something?
--
Steven
More information about the Python-ideas
mailing list