Skip to content
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
6 changes: 5 additions & 1 deletion mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -2595,7 +2595,11 @@ def bool_type(self) -> Instance:
def narrow_type_from_binder(self, expr: Expression, known_type: Type) -> Type:
if literal(expr) >= LITERAL_TYPE:
restriction = self.chk.binder.get(expr)
if restriction:
# If the current node is deferred, some variables may get Any types that they
# otherwise wouldn't have. We don't want to narrow down these since it may
# produce invalid inferred Optional[Any] types, at least.
if restriction and not (isinstance(known_type, AnyType)
and self.chk.current_node_deferred):
ans = narrow_declared_type(known_type, restriction)
return ans
return known_type
Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-optional.test
Original file line number Diff line number Diff line change
Expand Up @@ -673,3 +673,19 @@ class A:
lambda: (self.y, x.a) # E: Cannot determine type of 'y'
self.y = int()
[builtins fixtures/isinstancelist.pyi]

[case testDeferredAndOptionalInferenceSpecialCase]
def f() -> str:
y
x = None
if int():
x = ''
if x is None:
x = ''
g(x)
return x

def g(x: str) -> None: pass

y = int()
[builtins fixtures/bool.pyi]