python / python/typing

Fixed-size, multi-type sequence

Open
#592 3 comments 13 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: feature
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

This came up in python/typeshed#2287, but I have encountered the same problem myself. As far as I know, currently the only way to annotate a multi-type, fixed length sequence is using Tuple. But for input types this is often too strict:

def foo(x: Tuple[int, str]) -> None:
    a, b = x

def bar(x: Tuple[int, str]) -> None:
    a = x[0]
    b = x[1]

The implementations accept any iterable (first case) or sequence (second case) that yield two values:

class Iter:
    def __iter__(self):
        yield 1
        yield ""

foo((1, ""))
foo([1, ""])
foo(Iter())
bar((1, ""))
bar([1, ""])

It would be useful to have a way to annotate this. Of course type checkers would still need to reject generic cases like this:

def foo(x: TupleLike[str, str]): ...
x: List[str] = ...
foo(x)

But it could allow some things that are not possible at the moment, and opens the possibility for future improvements.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading python/typeshed#2287 and the examples in this issue, then review how typing currently represents tuples, iterables, and sequences. The issue does not name implementation files or tests; done would require an agreed annotation design that supports the described inputs while preserving useful type-checking restrictions.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.