Typing: Is there a "cast operator"?

Dan Stromberg drsalists at gmail.com
Sun Oct 23 23:14:15 EDT 2022


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.


More information about the Python-list mailing list