From c99133f405f286ed3429c809e9ae2cb3faaa2ceb Mon Sep 17 00:00:00 2001 From: Max Murin Date: Fri, 17 Feb 2023 17:05:35 -0800 Subject: [PATCH] Fix for bug with `in` operation on optionals in `no-strict-optional` mode (#14727) Fixes a bug introduced in https://github.com/python/mypy/pull/14384 wherein a union that includes `None` is no longer treated as a valid right-hand type for the `in` operator in `no-strict-optional` mode. (The reported error is `error: "None" has no attribute "__iter__" (not iterable) [attr-defined]`) --- mypy/checkexpr.py | 2 +- test-data/unit/check-optional.test | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 754ba6f093f5..38b5c2419d95 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -2950,7 +2950,7 @@ def visit_comparison_expr(self, e: ComparisonExpr) -> Type: right_type = get_proper_type(right_type) item_types: Sequence[Type] = [right_type] if isinstance(right_type, UnionType): - item_types = list(right_type.items) + item_types = list(right_type.relevant_items()) sub_result = self.bool_type() diff --git a/test-data/unit/check-optional.test b/test-data/unit/check-optional.test index db07290f7b40..754c6b52ff19 100644 --- a/test-data/unit/check-optional.test +++ b/test-data/unit/check-optional.test @@ -1031,3 +1031,12 @@ def f1(b: bool) -> Optional[int]: class Defer: def __init__(self) -> None: self.defer = 10 + +[case testOptionalIterator] +# mypy: no-strict-optional +from typing import Optional, List + +x: Optional[List[int]] +if 3 in x: + pass +