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

Fixes 'in' operator rejected with union type operand #9571

Closed
wants to merge 5 commits into from
Closed
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
19 changes: 17 additions & 2 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -2202,13 +2202,28 @@ def visit_comparison_expr(self, e: ComparisonExpr) -> Type:
# will be reported for types incompatible with __contains__().
# See testCustomContainsCheckStrictEquality for an example.
cont_type = self.chk.analyze_container_item_type(right_type)
iter_type = right_type
changed_expr = right
proper_right_type = get_proper_type(right_type)
if (local_errors.is_errors() and
isinstance(proper_right_type, UnionType)):
typs = [] # type: List[Type]
for item in proper_right_type.relevant_items():
temp_errors = self.msg.copy()
temp_errors.disable_count = 0
self.check_method_call_by_name(
'__contains__', item, [left], [ARG_POS], e, temp_errors)
if temp_errors.is_errors():
typs.append(item)
iter_type = UnionType.make_union(typs)
changed_expr = TempNode(iter_type)
if isinstance(right_type, PartialType):
# We don't really know if this is an error or not, so just shut up.
pass
elif (local_errors.is_errors() and
# is_valid_var_arg is True for any Iterable
self.is_valid_var_arg(right_type)):
_, itertype = self.chk.analyze_iterable_item_type(right)
self.is_valid_var_arg(iter_type)):
_, itertype = self.chk.analyze_iterable_item_type(changed_expr)
method_type = CallableType(
[left_type],
[nodes.ARG_POS],
Expand Down
9 changes: 9 additions & 0 deletions test-data/unit/check-expressions.test
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,15 @@ class D(Iterable[A]):
def __iter__(self) -> Iterator[A]: pass
[builtins fixtures/bool.pyi]

[case testInOperatorUnion]
from typing import Iterable, Union, Container
u: Union[Iterable[str], Container[str], Iterable[str]]
'x' in u

w: Union[Container[str], int]
'x' in w # E: Unsupported right operand type for in ("Union[Container[str], int]")
[typing fixtures/typing-full.pyi]

[case testNotInOperator]
from typing import Iterator, Iterable, Any
a, b, c, d, e = None, None, None, None, None # type: (A, B, bool, D, Any)
Expand Down