8000 Fix union inference of generic class and its generic type by roberfi · Pull Request #17310 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Fix union inference of generic class and its generic type #17310

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

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
Next Next commit
Fix union inference of generic class and its generic type
  • Loading branch information
roberfi committed Jun 1, 2024
commit b1d5b923615d8b6d348227e5ae52e909b35400e0
16 changes: 15 additions & 1 deletion mypy/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,10 +390,24 @@ def _infer_constraints(
# When the template is a union, we are okay with leaving some
# type variables indeterminate. This helps with some special
# cases, though this isn't very principled.

def _is_item_being_overlaped_by_other(item: Type) -> bool:
# It returns true if the item is an argument of other item
# that is subtype of the actual type
return any(
isinstance(p_type := get_proper_type(item_to_compare), Instance)
and mypy.subtypes.is_subtype(actual, erase_typevars(p_type))
and item in p_type.args
for item_to_compare in template.items
if item is not item_to_compare
)

result = any_constraints(
[
infer_constraints_if_possible(t_item, actual, direction)
for t_item in template.items
for t_item in [
item for item in template.items if not _is_item_being_overlaped_by_other(item)
]
],
eager=False,
)
Expand Down
30 changes: 23 additions & 7 deletions test-data/unit/check-inference.test
Original file line number Diff line number Diff line change
Expand Up @@ -873,13 +873,7 @@ def g(x: Union[T, List[T]]) -> List[T]: pass
def h(x: List[str]) -> None: pass
g('a')() # E: "List[str]" not callable

# The next line is a case where there are multiple ways to satisfy a constraint
# involving a Union. Either T = List[str] or T = str would turn out to be valid,
# but mypy doesn't know how to branch on these two options (and potentially have
# to backtrack later) and defaults to T = Never. The result is an
# awkward error message. Either a better error message, or simply accepting the
# call, would be preferable here.
g(['a']) # E: Argument 1 to "g" has incompatible type "List[str]"; expected "List[Never]"
g(['a'])

h(g(['a']))

Expand All @@ -891,6 +885,28 @@ i(b, a, b)
i(a, b, b) # E: Argument 1 to "i" has incompatible type "List[int]"; expected "List[str]"
[builtins fixtures/list.pyi]

[case testUnionInferenceOfGenericClassAndItsGenericType]
from typing import Generic, TypeVar, Union

T = TypeVar('T')

class GenericClass(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value

def method_with_union(arg: Union[GenericClass[T], T]) -> GenericClass[T]:
if not isinstance(arg, GenericClass):
arg = GenericClass(arg)
return arg

result_1 = method_with_union(GenericClass("test"))
reveal_type(result_1) # N: Revealed type is "__main__.GenericClass[builtins.str]"

result_2 = method_with_union("test")
reveal_type(result_2) # N: Revealed type is "__main__.GenericClass[builtins.str]"

[builtins fixtures/isinstance.pyi]

[case testCallableListJoinInference]
from typing import Any, Callable

Expand Down
0