Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix type comments crash inside generic definitions #16849

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 11 additions & 1 deletion mypy/expandtype.py
Expand Up @@ -2,7 +2,7 @@

from typing import Final, Iterable, Mapping, Sequence, TypeVar, cast, overload

from mypy.nodes import ARG_STAR, Var
from mypy.nodes import ARG_STAR, FakeInfo, Var
from mypy.state import state
from mypy.types import (
ANY_STRATEGY,
Expand Down Expand Up @@ -207,6 +207,16 @@ def visit_erased_type(self, t: ErasedType) -> Type:

def visit_instance(self, t: Instance) -> Type:
args = self.expand_types_with_unpack(list(t.args))

if isinstance(t.type, FakeInfo):
# The type checker expands function definitions and bodies
# if they depend on constrained type variables but the body
# might contain a tuple type comment (e.g., # type: (int, float)),
# in which case 't.type' is not yet available.
#
# See: https://github.com/python/mypy/issues/16649
return t.copy_modified(args=args)

if t.type.fullname == "builtins.tuple":
# Normalize Tuple[*Tuple[X, ...], ...] -> Tuple[X, ...]
arg = args[0]
Expand Down
26 changes: 26 additions & 0 deletions test-data/unit/check-typevar-values.test
Expand Up @@ -706,3 +706,29 @@ Func = Callable[[], T]

class A: ...
class B: ...

[case testTypeCommentInGenericTypeWithConstrainedTypeVar]
from typing import Generic, TypeVar

NT = TypeVar("NT", int, float)

class Foo1(Generic[NT]):
p = 1 # type: int

class Foo2(Generic[NT]):
p, q = 1, 2.0 # type: (int, float)

class Foo3(Generic[NT]):
def bar(self) -> None:
p = 1 # type: int

class Foo4(Generic[NT]):
def bar(self) -> None:
p, q = 1, 2.0 # type: (int, float)

def foo3(x: NT) -> None:
p = 1 # type: int

def foo4(x: NT) -> None:
p, q = 1, 2.0 # type: (int, float)
[builtins fixtures/tuple.pyi]