Skip to content

Support for Union[*TypeVarTuple] #1523

Closed

Description

@pwuertz

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

Activity

  1. added
    topic: featureDiscussions about new features for Python's type annotations
    on Dec 4, 2023
  2. erictraut commented on Dec 22, 2023

    @erictraut
    Collaborator

    This is simply a missing piece of functionality in mypy. I recommend closing this issue and opening a corresponding one in the mypy issue tracker to it gets the attention of the mypy maintainers.

    FWIW, the above code type checks as expected in pyright.

  3. matt-gardner commented on Feb 1, 2024

    @matt-gardner

    Apologies if I'm missing something, but did pyright's behavior change since the above comment was written? When I click on the link to the pyright playground, I see a failure on line 7.

  4. erictraut commented on Feb 1, 2024

    @erictraut
    Collaborator

    Yes, pyright's behavior changed since the above comment. Unbeknownst to me, the PEP 646 authors removed the Union[*Ts] capability prior to the PEP's acceptance. I implemented pyright's PEP 646 support prior to this removal. Since the final version of the PEP removed the notion of Union[*Ts], I likewise removed support for it in pyright.

    If you would like to see Union[*Ts] become part of the type spec, that would require a new PEP, or at least a public discussion in the Typing forum, a proposed modification to the spec, and approval by the Typing Council.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions