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

Devin Jeanpierre jeanpierreda at gmail.com
Sun Aug 17 14:05:24 CEST 2014


On Sun, Aug 17, 2014 at 4:44 AM, 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.
>
> It doesn't accept lists, because then it would need to check for cycles.

I was going to leave it at that -- the fact that a builtin works this
way is an argument in favor of any standardized typing syntax
supporting it -- but maybe it deserves justification, too.

The key question is, given two values A and B that are valid second
parameters to isinstance, how do you combine them into one valid
second parameter, which forms the union of A and B? if A and B were
always tuples, you could do A + B (isinstance predates sets). But we
want to be able to do isinstance(x, SomeType), so A and B can't always
be tuples. So Python adopts the convention that you can do (A, B) and,
no matter what they are, isinstance(x, (A, B)) holds if and only if
(isinstance(x, A) or isinstance(x, B)).

As it happens we could use frozensets instead, but, oops. Given that
frozensets are out of the question (in this case, because of dating,
in other cases, because of unhashability or whatever) using sequences
seems reasonable, and specifically using tuples so that we can avoid
cycle checks (a messy algorithm) also seems entirely reasonable.

I've also seen people use tuples to emphasize that the sequence is not
mutated, but there's no reason to require that from a type signature
in that case.

-- Devin


More information about the Python-ideas mailing list