Typing: Is there a "cast operator"?

Paulo da Silva p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt
Sun Oct 23 16:36:21 EDT 2022


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.

Thank you.



More information about the Python-list mailing list