Upgrade tuples returned in stdlib functions to namedtuples

(Terry Davis) #1

While using inspect.getsourcelines, I had a moment of confusion. I had looked at the docs briefly before invoking the function, but it was not obvious which element of the tuple was the first line number and which was the list of source lines. It would be nice if the result was a named tuple defined like so: namedtuple('SourceLines', 'lines line_no').
This could be applied more broadly across the standard library. It would be a form of self-documenting code, and improve readability & discoverability.

3 Likes
(Martijn Pieters) #2

Where it makes sense, this already is the case, including the inspect library, which in Python 3.7 defines 9 named tuples.

I’m not sure that it makes that much sense for this specific API; a function that is documented to return a lines, lineno tuple doesn’t gain much from naming the two elements. Defining namedtuple classes for each and every function that returns two items carries a maintenance burden too! And I strongly suspect that namedtuple classes can’t make use of the small-tuple cache (used to significantly lower the cost of creating and destroying tuples).

(Pablo Galindo Salgado) #3

I would even say that this is a bad choice because it makes very difficult to extend the return values to include a new argument. For example, when making the changes for PEP 570, adding new fields to the Arguments name tuple was technically backwards incompatible.

1 Like
(Marc-André Lemburg) #4

Tuple creation is one of the fastest object creation processes
in Python. Namedtuple creation is significantly slower, so each
such case has to be looked at from a performance / usability
tradeoff point of view.

1 Like
(Serhiy Storchaka) #5

Not only creation. Many other operations are faster with tuples than with named tuple because much code is specialized for exact tuples. Named tuples can lead to larger memory fragmentation.

1 Like