-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Type of variable after isinstance check with 'and' #473
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This already works if the condition only has an def f(x: A) -> None:
if isinstance(x, B):
print(x.value) # Ok
class A:
pass
class B(A):
value = 0 Mypy should support more cases, including Here is another case that could be useful (this could be a separate issue): def f(x: object) -> None:
if isinstance(x, int) or isinstance(x, str): # or isinstance(x, (int, str))
# type of x should be Union[int, str]
pass These improvements are important for proper type checking of def f(x: Union[int, None]) -> None:
if x and x > 3: # Ok
print(x * 2) # Ok
print(x * 2) # Error, since can't multiply None Currently there is no error reported for the the second print statement. |
Just to put it out there, the Cobra approach (see Compile-time Nil Tracking) to null values seems nicer, in my opinion, than using def x(a: Nullable[int]) -> int:
print(a*a) # ok; a is still an int
return a # error; cannot convert Nullable type to none-Nullable type
if a: return a # ok; a cannot be None |
My preferred spelling would be Optional[int]. (Nullable reeks of SQL. :-) On Sun, Oct 12, 2014 at 1:57 PM, Ryan Gonzalez [email protected]
--Guido van Rossum (python.org/~guido) |
@gvanrossum You're very right; I like Optional better. |
@kirbyfan64 I agree, special syntax would be preferable. But I'm not sure why |
Added issue #477 for |
After a guard with
isinstance
, mypy should consider the variable to be of that type.For example:
Here, mypy reports that
x
doesn't have a fieldvalue
. This can of course be solved with a cast, but that is annoying to type and clutters the code. At least in simple case, mypy could infer thatx
is of typeB
in the rhs of the and-statement and in the block following the if-statement.The text was updated successfully, but these errors were encountered: