python / python/mypy

Support for Union[*TypeVarTuple]

Open
#16,720 4 comments 13 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-pep-646
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

(Forwarded from https://github.com/python/typing/issues/1523)
I'm trying to annotate a method that only accepts a union of specific types, with the types specified via variadic generic. Although mypy supports variadic unpacking like Tuple[*Ts], unpacking Union[*Ts] doesn't seem to work yet:

import typing

Ts = typing.TypeVarTuple("Ts")

class Accepts(typing.Generic[*Ts]):
    # error: Unpack is only valid in a variadic position  [valid-type]
    def foo(self, x: typing.Union[*Ts]): ...

class A: ...
class B: ...
class C: ...
class Test(Accepts[A, B]): ...

Test().foo(A())  # ok
Test().foo(B())  # ok
Test().foo(C())  # should raise [arg-type] error

Mypy 1.7.1, Python 3.11

Contributor guide

Open the contributing guide

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 reproducing the example with mypy 1.7.1 on Python 3.11 and confirm the current diagnostic for Union[*Ts]. Trace the existing variadic unpacking support from the reported valid-type error. Done means Union[*Ts] is accepted and the example permits A and B while rejecting C with an arg-type error.

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
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.