You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Sometimes it is useful to narrow down a type after an in/not in comparison. For example:
classOption:
...
opt: Union[Option, str]
ifoptin ('verbose', 'silent'):
reveal_type(opt) # we know this is 'str'else:
... # still a union herepresets: List[Option]
ifoptnotinpresets:
... # still a unionelse:
reveal_type(opt) # we know this can be only 'Option'
This seems to be especially useful for --strict-optional, for example:
classNode:
fullname: Optional[str]
n: Nodereverse_aliases: Dict[str, str]
ifn.fullnameinreverse_aliases:
reveal_type(n.fullname) # This should be 'str'
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.
Careful. For unconstrained x, after x in (1, 2), x may still be a float. (Or a fraction or decimal?)
OK, makes sense, we should not narrow down if we start from Any and should not use promotions (this is actually default in is_overlapping_types). I will update the PR now.
Activity
elazarg commentedon Oct 8, 2017
I think this can also fall out of #4063 (just as a note; of course a dedicated PR is more practical)
gvanrossum commentedon Oct 8, 2017
ilevkivskyi commentedon Oct 8, 2017
@gvanrossum
OK, makes sense, we should not narrow down if we start from
Anyand should not use promotions (this is actually default inis_overlapping_types). I will update the PR now.ilevkivskyi commentedon Oct 8, 2017
@gvanrossum OK, I updated PR #4072
Now it does not narrow type from
Anyand does not use promotions:It is however not easy to prohibit this:
This is still formally speaking unsafe, but I think it is a reasonable price to pay.
Narrow types after 'in' operator (#4072)