Typing: Is there a "cast operator"?

Cameron Simpson cs at cskk.id.au
Sun Oct 23 18:56:07 EDT 2022


On 23Oct2022 21:36, Paulo da Silva <p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt> wrote:
>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.

Maybe you shouldn't. The other way is to just not initialise the var at 
all. You could then just specify a type. Example:

    Python 3.8.13 (default, Aug 11 2022, 15:46:53)
    [Clang 12.0.0 (clang-1200.0.32.29)] on darwin
    Type "help", "copyright", "credits" or "license" for more 
    information.
    >>> f:int
    >>> f
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'f' is not defined
    >>>

So now `f` has `int` type definitely (for `mypy`'s purposes), and if 
used before assignment raises a distinctive error (versus having the 
value `None`, which you might then pass around, and perhaps successfully 
use in some contexts).

It is probably better on the whole to specify types up front rather than 
relying on `mypy` or similar to infer them. That way (a) you're stating 
your intent and (b) not relying on an inferred type, which if you've got 
bugs may be inferred _wrong_. If `mypy` infers a type incorrectly all 
the subsequent checks will also be flawed, perhaps subtly.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list