Skip to content

Commit

Permalink
Stricter None handling with --no-strict-optional (#11717)
Browse files Browse the repository at this point in the history
Closes #11705
  • Loading branch information
sobolevn authored Jan 6, 2022
1 parent e0a89b7 commit e8cf960
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 8 deletions.
13 changes: 6 additions & 7 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -4550,17 +4550,16 @@ def has_no_custom_eq_checks(t: Type) -> bool:
self._check_for_truthy_type(original_vartype, node)
vartype = try_expanding_sum_type_to_union(original_vartype, "builtins.bool")

if_type = true_only(vartype) # type: Type
else_type = false_only(vartype) # type: Type
ref = node # type: Expression
if_type = true_only(vartype)
else_type = false_only(vartype)
if_map = (
{ref: if_type}
if not isinstance(get_proper_type(if_type), UninhabitedType)
{node: if_type}
if not isinstance(if_type, UninhabitedType)
else None
)
else_map = (
{ref: else_type}
if not isinstance(get_proper_type(else_type), UninhabitedType)
{node: else_type}
if not isinstance(else_type, UninhabitedType)
else None
)
return if_map, else_map
Expand Down
5 changes: 4 additions & 1 deletion mypy/typeops.py
Original file line number Diff line number Diff line change
Expand Up @@ -704,7 +704,10 @@ class Status(Enum):
typ = get_proper_type(typ)

if isinstance(typ, UnionType):
items = [try_expanding_sum_type_to_union(item, target_fullname) for item in typ.items]
items = [
try_expanding_sum_type_to_union(item, target_fullname)
for item in typ.relevant_items()
]
return make_simplified_union(items, contract_literals=False)
elif isinstance(typ, Instance) and typ.type.fullname == target_fullname:
if typ.type.is_enum:
Expand Down
30 changes: 30 additions & 0 deletions test-data/unit/check-inference.test
Original file line number Diff line number Diff line change
Expand Up @@ -3210,3 +3210,33 @@ def test(seq: List[Union[Iterable, Any]]) -> None:
k = [k]
reveal_type(k) # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testRegression11705_Strict]
# flags: --strict-optional
# See: https://github.com/python/mypy/issues/11705
from typing import Dict, Optional, NamedTuple
class C(NamedTuple):
x: int

t: Optional[C]
d: Dict[C, bytes]
x = t and d[t]
reveal_type(x) # N: Revealed type is "Union[None, builtins.bytes*]"
if x:
reveal_type(x) # N: Revealed type is "builtins.bytes*"
[builtins fixtures/dict.pyi]

[case testRegression11705_NoStrict]
# flags: --no-strict-optional
# See: https://github.com/python/mypy/issues/11705
from typing import Dict, Optional, NamedTuple
class C(NamedTuple):
x: int

t: Optional[C]
d: Dict[C, bytes]
x = t and d[t]
reveal_type(x) # N: Revealed type is "builtins.bytes*"
if x:
reveal_type(x) # N: Revealed type is "builtins.bytes*"
[builtins fixtures/dict.pyi]

0 comments on commit e8cf960

Please sign in to comment.