4 ms·
> There is no reason for this to expose a tuple API. FWIW, that is a norm in the standard library that predates named tuples. For example, sys.version_info an
by raymondh 9y ago
> There is no reason for this to expose a tuple API.
FWIW, that is a norm in the standard library that predates named tuples.
For example, sys.version_info and time.localtime() return structseq instances. Those both have a named tuple API.
The are tuple subclasses with named fields. Accordingly, they are indexable, iterable, hashable, space-efficient, and have a self-documenting __repr__().
- eesmith 9y agoIn my original comment I wrote "'namedtuple' has one good use - migration from a tuple object to a real object while allowing backwards compatability to the tuple API. For example, the old tuples once returned from os.stat() and time.gmtime()." The two examples you gave are examples of that good use. The time.localtime() used to return a tuple. See https://github.com/python/cpython/blob/770e4042db8a1c277b5d9b678cf6045a7aa2bd33/Modules/timemodule.c#L232 https://github.com/python/cpython/blob/770e4042db8a1c277b5d9... . The change to StructTimeType is an example of how to do that sort of migration. Similarly, sys.version_info() used to return a tuple. See https://github.com/python/cpython/blob/193a3f6d37c1440b049f7b1c62ff30c1d8cae38a/Python/sysmodule.c#L764 https://github.com/python/cpython/blob/193a3f6d37c1440b049f7... . Again, a good example of how to migrate. However, the "this" in the "There is no reason for this to expose a tuple API" which you quoted refers specifically to the namedtuple that cache_info() returns. That did not replace a tuple, it replaced two attributes, as you can see at https://github.com/python/cpython/commit/234515afe594e5f9ca1b3f460735c68b04c031e2#diff-da04cc419a12dd6f8b6f44e11a459ef https://github.com/python/cpython/commit/234515afe594e5f9ca1... . And returning a simple type with a couple of attributes while also (and needlessly) treating it as a tuple was never a norm in Python before namedtuples, if only because it was a lot of work.
- xapata 9y ago> it was a lot of work Thus the desire for types.SimpleNamespace as others have noted. Though we might have better design choices today than yesterday, there's also a downside to code churn. Case in point the annoyance of trying to modernize threading from isAlive to is_alive. Even when writing new code, it's often wiser to stick with a "worse" standard than to use a new design.
- eesmith 9y agoI agree with all of that (with the proviso that the SimpleNamespace documentation doesn't make it sound desirable). I disagree with raymondh's statement that "that is a norm in the standard library that predates named tuples."