[Python-ideas] Variable-length, homogeneous tuple: why? (was: Optional static typing -- the crossroads)

Nick Coghlan ncoghlan at gmail.com
Sun Aug 17 14:43:45 CEST 2014


On 17 August 2014 21:44, Devin Jeanpierre <jeanpierreda at gmail.com> wrote:
> On Sun, Aug 17, 2014 at 1:23 AM, Ben Finney <ben+python at benfinney.id.au> wrote:
>> I have encountered many uses of “homogeneous, variable-length sequence”
>> and every time a Python tuple is used for that, I perceive a Python list
>> would be better precisely *because* it better indicates that semantic
>> meaning.
>>
>> I'd like to know how you think that's not true, and what real-world code
>> makes you think so.
>
> isinstance is real world code that for the second parameter accepts
> types and (recursively) tuples of any length of things it accepts.

There are a few other cases where tuples are special cased as arguments:

- str.__mod__
- str.startswith (ditto for binary sequences)
- str.endswith (ditto for binary sequences)

>>> "aa".endswith(['a', 'b', 'c'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: endswith first arg must be str or a tuple of str, not list

Searching the C files for "tuple of" turned up a couple more:

* N-dimensional indexing also relies specifically on
tuples-of-integers, rather than arbitrary iterators.

* dynamic type creation expects to receive the bases as a tuple

* the decimal module uses tuples of digits for internal data representations

And that inspired recollection of several other cases where mutability
would be wrong, because the tuple represents cached information rather
than dynamic state:

* various "*args" related APIs use "tuple of object" or "tuple of
thing" (e.g. attributes of partial objects, internal storage in
contextlib.ExitStack when used with arbitrary callbacks)

* other introspection related APIs use tuples to report information
about inspected objects

* namedtuple _fields attributes are a tuple of strings

* BaseException.args publishes the full args tuple passed to the constructor

str.startswith, str.endswith, isinstance and issubclass use the
"implied or" interpretation, everything else does not. In most cases,
the immutability conveys relevant semantic information (usually
indicating that it's a read-only API).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list