Skip to content

Update the overlapping check for tuples to account for NamedTuples #18564

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 4 commits into from
Jan 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
12 changes: 11 additions & 1 deletion mypy/meet.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
find_unpack_in_list,
get_proper_type,
get_proper_types,
is_named_instance,
split_with_prefix_and_suffix,
)

Expand Down Expand Up @@ -645,7 +646,16 @@ def are_tuples_overlapping(

if len(left.items) != len(right.items):
return False
return all(is_overlapping(l, r) for l, r in zip(left.items, right.items))
if not all(is_overlapping(l, r) for l, r in zip(left.items, right.items)):
return False

# Check that the tuples aren't from e.g. different NamedTuples.
if is_named_instance(right.partial_fallback, "builtins.tuple") or is_named_instance(
left.partial_fallback, "builtins.tuple"
):
return True
else:
return is_overlapping(left.partial_fallback, right.partial_fallback)


def expand_tuple_if_possible(tup: TupleType, target: int) -> TupleType:
Expand Down
32 changes: 32 additions & 0 deletions test-data/unit/check-namedtuple.test
Original file line number Diff line number Diff line change
Expand Up @@ -1474,3 +1474,35 @@ def main(n: NT[T]) -> None:

[builtins fixtures/tuple.pyi]
[typing fixtures/typing-namedtuple.pyi]

[case testNamedTupleOverlappingCheck]
from typing import overload, NamedTuple, Union

class AKey(NamedTuple):
k: str

class A(NamedTuple):
key: AKey


class BKey(NamedTuple):
k: str

class B(NamedTuple):
key: BKey

@overload
def f(arg: A) -> A: ...
@overload
def f(arg: B) -> B: ...
def f(arg: Union[A, B]) -> Union[A, B]: ...

def g(x: Union[A, B, str]) -> Union[A, B, str]:
if isinstance(x, str):
return x
else:
reveal_type(x) # N: Revealed type is "Union[Tuple[Tuple[builtins.str, fallback=__main__.AKey], fallback=__main__.A], Tuple[Tuple[builtins.str, fallback=__main__.BKey], fallback=__main__.B]]"
return x._replace()

# no errors should be raised above.
[builtins fixtures/tuple.pyi]