Closed
Description
Sometimes it is useful to narrow down a type after an in
/not in
comparison. For example:
class Option:
...
opt: Union[Option, str]
if opt in ('verbose', 'silent'):
reveal_type(opt) # we know this is 'str'
else:
... # still a union here
presets: List[Option]
if opt not in presets:
... # still a union
else:
reveal_type(opt) # we know this can be only 'Option'
This seems to be especially useful for --strict-optional
, for example:
class Node:
fullname: Optional[str]
n: Node
reverse_aliases: Dict[str, str]
if n.fullname in reverse_aliases:
reveal_type(n.fullname) # This should be 'str'
(related #2980)
A similar idea was discussed in #1749, but emitting an error on if 'a' in [1, 2, 3]: ...
would require a larger change: emitting errors on unreachable code in binder.
Metadata
Metadata
Assignees
Labels
No labels