Typing: Is there a "cast operator"?
Thomas Passin
list1 at tompassin.net
Mon Oct 24 01:24:10 EDT 2022
On 10/23/2022 11:14 PM, Dan Stromberg wrote:
> On Sun, Oct 23, 2022 at 2:11 PM Paulo da Silva <
> p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt> wrote:
>
>> Hello!
>>
>> I am in the process of "typing" of some of my scripts.
>> Using it should help a lot to avoid some errors.
>> But this is new for me and I'm facing some problems.
>>
>> Let's I have the following code (please don't look at the program content):
>>
>> f=None # mypy naturally assumes Optional(int) because later, at open,
>> it is assigned an int.
>> ..
>> if f is None:
>> f=os.open(...
>> ..
>> if f is not None:
>> os.write(f, ...)
>> ..
>> if f is not None:
>> os.close(f)
>>
>> When I use mypy, it claims
>> Argument 1 to "write" has incompatible type "Optional[int]"; expected "int"
>> Argument 1 to "close" has incompatible type "Optional[int]"; expected "int"
>>
>> How to solve this?
>> Is there a way to specify that when calling os.open f is an int only?
>>
>> I use None a lot for specify uninitialized vars.
>>
>
> I've found that mypy understands simple assert statements.
>
> So if you:
> if f is not None:
> assert f is not None
> os.write(f, ...)
>
> You might be in good shape.
I'm not very familiar with anything but the simplest typing cases as
yet, but mypy is happy with these two fragments.
if f:
os.write(int(f)) # f must be an int if it is not None, so we can
cast it to int.
Or something like this (substitute write() for print() as needed) -
from typing import Optional, Any
def f1(x:int)->Optional[int]:
if x == 42:
return x
return None
def zprint(arg:Any):
if type(arg) == int:
print(arg)
y0 = f1(0) # None
y42 = f1(42) # 42
zprint(y0) # Prints nothing
zprint(y42) # Prints 42
Another possibility that mypy is happy with (and probably the simplest)
- just declare g:int = None instead of g = None:
g: int = None
def yprint(arg: int):
if arg:
yprint(arg)
else:
print('arg is None')
yprint(g) # Prints "arg is None"
And **please** let's not go doing this kind of redundant and inelegant
construction:
if f is not None:
assert f is not None
os.write(f, ...)
More information about the Python-list
mailing list