Typing: Is there a "cast operator"?

Peter Otten __peter__ at web.de
Wed Oct 26 08:44:29 EDT 2022


On 24/10/2022 05:19, Chris Angelico wrote:
> On Mon, 24 Oct 2022 at 14:15, Dan Stromberg <drsalists at gmail.com> wrote:
>> 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.
>
> Why can't it simply understand the if statement?

Could it be that this specific problem is fixed in current mypy?
I get

$ type .\tmp.py
import os

f = None
if f is None:
     f = os.open("tmp.txt", os.O_RDWR|os.O_CREAT)
os.write(f, b"yadda")
$ mypy tmp.py
Success: no issues found in 1 source file

My attempt to verify that

if name is None: ...

is recognized:

$ type .\tmp2.py
import os
import random

f = None
if random.randrange(2):
     f = os.open("tmp.txt", os.O_RDWR|os.O_CREAT)
os.write(f, b"yadda")
$ mypy tmp2.py
tmp2.py:7: error: Argument 1 to "write" has incompatible type
"Optional[int]"; expected "int"
Found 1 error in 1 file (checked 1 source file)
$ mypy --version
mypy 0.982 (compiled: yes)
$

I'm not a fan of
> coddling a type system like this. The entire point of type checking is
> to help you find bugs more efficiently, so if you have to repeat
> yourself every time you do these kinds of checks just so that mypy is
> satisfied, that's counter-productive (case in point: what happens if
> you say "if fn is not None: assert f is not None"? Now you've
> introduced a bug just to deal with the type system).
>
> ChrisA



More information about the Python-list mailing list