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
Mypy doesn't allow things like type(x) is int to be used to narrow down types, since this doesn't cover any subtypes of int. Maybe we should generate an error and suggest using isinstance(...) instead. Since this could be noisy, perhaps we should only do this if x is a union type.
Alternatively, we could support this as a valid type check, but treat it as an incomplete type check. This code would therefore still generate an error (but only one error):
deff(x: Union[int, str]) ->None:
iftype(x) isint:
returnx+1# Should be okay? (currently generates an error)else:
returnx+'foo'# Still an error, since 'x' could be a subtype of 'int'
Also, if the target type X is final, using type(x) is X instead of isinstance() would be technically fine, though it's still stylistically suspect.
See #7258 for an example where this caused confusion.
The text was updated successfully, but these errors were encountered:
I think I am fine with supporting this. This is a bad style but we probably should not be too opinionated about style in cases where we can do safe reasoning about the code. I think we can indeed show only error in the second branch, and not show any errors at all in case of a final class.
Using type(C) is int for type narrowing is now documented as being supported, and the example now works as expected on mypy 0.942, so I'm closing this. (Feel free to reopen if I'm mistaken!)
deff(x: int|str) ->None:
iftype(x) isint:
x+1# No error on mypy 0.942else:
x+'foo'# error: Unsupported operand types for + ("int" and "str") # note: Left operand is of type "Union[int, str]"
Mypy doesn't allow things like
type(x) is int
to be used to narrow down types, since this doesn't cover any subtypes ofint
. Maybe we should generate an error and suggest usingisinstance(...)
instead. Since this could be noisy, perhaps we should only do this ifx
is a union type.Alternatively, we could support this as a valid type check, but treat it as an incomplete type check. This code would therefore still generate an error (but only one error):
Also, if the target type
X
is final, usingtype(x) is X
instead ofisinstance()
would be technically fine, though it's still stylistically suspect.See #7258 for an example where this caused confusion.
The text was updated successfully, but these errors were encountered: