Skip to content

Improve type inference special case that involves union with Any #10887

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 1 commit into from
Jul 28, 2021
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
10 changes: 10 additions & 0 deletions mypy/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,16 @@ def any_constraints(options: List[Optional[List[Constraint]]], eager: bool) -> L
# TODO: More generally, if a given (variable, direction) pair appears in
# every option, combine the bounds with meet/join.
return valid_options[0]
elif len(valid_options) > 1:
# Drop constraints that only refer to "Any" and try again. This way Any types
# in unions don't interfere with type inference.
narrowed_options = [option
for option in valid_options
if not (option and
all(isinstance(get_proper_type(c.target), AnyType)
for c in option))]
if len(narrowed_options) < len(valid_options):
return any_constraints([option for option in narrowed_options], eager)

# Otherwise, there are either no valid options or multiple, inconsistent valid
# options. Give up and deduce nothing.
Expand Down
8 changes: 8 additions & 0 deletions test-data/unit/check-inference-context.test
Original file line number Diff line number Diff line change
Expand Up @@ -1375,3 +1375,11 @@ def f(x: Callable[..., T]) -> T:

x: G[str] = f(G)
[out]

[case testConditionalExpressionWithEmptyListAndUnionWithAny]
from typing import Union, List, Any

def f(x: Union[List[str], Any]) -> None:
a = x if x else []
reveal_type(a) # N: Revealed type is "Union[builtins.list[builtins.str], Any]"
[builtins fixtures/list.pyi]