8000 Enable generic NamedTuples by ilevkivskyi · Pull Request #13396 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Enable generic NamedTuples #13396

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

Merged
merged 7 commits into from
Aug 15, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Better logic for recursive generic named tuples
  • Loading branch information
ilevkivskyi committed Aug 12, 2022
commit 417fc57906588f9e23c786f124850dcf39b18d43
8 changes: 8 additions & 0 deletions mypy/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,14 @@ def visit_tuple_type(self, template: TupleType) -> List[Constraint]:
]

if isinstance(actual, TupleType) and len(actual.items) == len(template.items):
if (
actual.partial_fallback.type.is_named_tuple
and template.partial_fallback.type.is_named_tuple
):
# For named tuples using just the fallbacks usually gives better results.
return infer_constraints(
template.partial_fallback, actual.partial_fallback, self.direction
)
res: List[Constraint] = []
for i in range(len(template.items)):
res.extend(infer_constraints(template.items[i], actual.items[i], self.direction))
Expand Down
11 changes: 6 additions & 5 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1381,10 +1381,7 @@ def analyze_class(self, defn: ClassDef) -> None:
if self.analyze_typeddict_classdef(defn):
return

if self.analyze_namedtuple_classdef(defn):
if defn.info:
self.setup_type_vars(defn, tvar_defs)
self.setup_alias_type_vars(defn)
if self.analyze_namedtuple_classdef(defn, tvar_defs):
return

# Create TypeInfo for class now that base classes and the MRO can be calculated.
Expand Down Expand Up @@ -1447,7 +1444,9 @@ def analyze_typeddict_classdef(self, defn: ClassDef) -> bool:
return True
return False

def analyze_namedtuple_classdef(self, defn: ClassDef) -> bool:
def analyze_namedtuple_classdef(
self, defn: ClassDef, tvar_defs: List[TypeVarLikeType]
) -> bool:
"""Check if this class can define a named tuple."""
if (
defn.info
Expand All @@ -1467,6 +1466,8 @@ def analyze_namedtuple_classdef(self, defn: ClassDef) -> bool:
self.mark_incomplete(defn.name, defn)
else:
self.prepare_class_def(defn, info, custom_names=True)
self.setup_type_vars(defn, tvar_defs)
self.setup_alias_type_vars(defn)
with self.scope.class_scope(defn.info):
with self.named_tuple_analyzer.save_namedtuple_body(info):
self.analyze_class_body_common(defn)
Expand Down
10 changes: 5 additions & 5 deletions test-data/unit/check-namedtuple.test
Original file line number Diff line number Diff line change
Expand Up @@ -1240,7 +1240,7 @@ foo(nts) # E: Argument 1 to "foo" has incompatible type "NT[str]"; expected "Tu
[case testGenericNamedTupleJoin]
from typing import Generic, NamedTuple, TypeVar, Tuple

T = TypeVar("T")
T = TypeVar("T", covariant=True)
class NT(NamedTuple, Generic[T]):
key: int
value: T
Expand All @@ -1249,12 +1249,12 @@ nts: NT[str]
nti: NT[int]
x: Tuple[int, ...]

def foo(x: T, y: T) -> T: ...
S = TypeVar("S")
def foo(x: S, y: S) -> S: ...
reveal_type(foo(nti, nti)) # N: Revealed type is "Tuple[builtins.int, builtins.int, fallback=__main__.NT[builtins.int]]"

# Here fallbacks are object because named tuples are invariant.
reveal_type(foo(nti, nts)) # N: Revealed type is "Tuple[builtins.int, builtins.object, fallback=builtins.object]"
reveal_type(foo(nts, nti)) # N: Revealed type is "Tuple[builtins.int, builtins.object, fallback=builtins.object]"
reveal_type(foo(nti, nts)) # N: Revealed type is "Tuple[builtins.int, builtins.object, fallback=__main__.NT[builtins.object]]"
reveal_type(foo(nts, nti)) # N: Revealed type is "Tuple[builtins.int, builtins.object, fallback=__main__.NT[builtins.object]]"

reveal_type(foo(nti, x)) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
reveal_type(foo(nts, x)) # N: Revealed type is "builtins.tuple[builtins.object, ...]"
Expand Down
24 changes: 24 additions & 0 deletions test-data/unit/check-recursive-types.test
8CC2
Original file line number Diff line numberDiff line change
Expand Up @@ -611,6 +611,30 @@ def foo() -> None:
reveal_type(b) # N: Revealed type is "Tuple[Any, builtins.int, fallback=__main__.B@4]"
[builtins fixtures/tuple.pyi]

[case testBasicRecursiveGenericNamedTuple]
# flags: --enable-recursive-aliases
from typing import Generic, NamedTuple, TypeVar, Union

T = TypeVar("T", covariant=True)
class NT(NamedTuple, Generic[T]):
key: int
value: Union[T, NT[T]]

class A: ...
class B(A): ...

nti: NT[int] = NT(key=0, value=NT(key=1, value=A())) # E: Argument "value" to "NT" has incompatible type "A"; expected "Union[int, NT[int]]"
reveal_type(nti) # N: Revealed type is "Tuple[builtins.int, Union[builtins.int, ...], fallback=__main__.NT[builtins.int]]"

nta: NT[A]
ntb: NT[B]
nta = ntb # OK, covariance
ntb = nti # E: Incompatible types in assignment (expression has type "NT[int]", variable has type "NT[B]")

def last(arg: NT[T]) -> T: ...
reveal_type(last(ntb)) # N: Revealed type is "__main__.B"
[builtins fixtures/tuple.pyi]

[case testBasicRecursiveTypedDictClass]
# flags: --enable-recursive-aliases
from typing import TypedDict
Expand Down
0