Mypy: Add type for variable-length tuples

Created on 4 Jul 2013  路  4Comments  路  Source: python/mypy

We should have a type for variable-length tuples. It could be called TupleSequence[T].

Example:

t = None # type: Tuple[int, ...]
t = (1, 2) # Okay
t = (1, 2, 3) # Okay
n = 1
print(t[n]) # Okay
for n in t: print(n) # Okay
t = [1, 2] # Error

It is needed for precise static typing of some builtins, such as str.startswith.

We would not (generally) infer these types automatically for variables: type inference would still produce Tuple[...] types.

Update: Actually, it seems more reasonable to have Tuple[...] as a subtype of TupleSequence[...] assuming type arguments are compatible. Also need to update type joins to handle these.

EDIT: Update to conform to the actual syntax.

feature topic-pep-484

Most helpful comment

PEP 484 draft uses Tuple[int, ...] (the dots are part of the syntax), which seems pretty reasonable and better than TupleSequence: https://github.com/ambv/typehinting/issues/30

It will also work in Python 2.

All 4 comments

PEP 484 draft uses Tuple[int, ...] (the dots are part of the syntax), which seems pretty reasonable and better than TupleSequence: https://github.com/ambv/typehinting/issues/30

It will also work in Python 2.

There are still some corner cases that aren't handled properly, but I pushed the implementation as it's good enough for many uses already.

Now to change all the stubs ...

I updated some obvious stub definitions already (startswith etc.), but I'm sure I missed a bunch.

Was this page helpful?
0 / 5 - 0 ratings