I'm a little confused as to why PyCharm doesn't distinguish between two different Optional types.
Consider the following code.
def funcs(foo:Optional[str]=None):
    print(foo)
def funci(var:Optional[int]=None):
    funcs(var)
argi = 1
args = "something"
argn = None
funcs(argi)
funcs(args)
funcs(argn)
Notice the funcs call inside funci doesn't see a problem with passing in an Optional[int] to a function that is looking for an Optional[str].

And yet, if we remove the Optional[str] the inspection barks.

Is this expected behavior? If yes, what can I do about it?
My gut says type checking should be smart enough to tell the difference between Optional[str] vs Optional[int].  I've read through PEP-526 and PEP-484 to no avail.
If you test this in the current version of PyCharm (2021.1) with default inspection settings, the second warning after removal of the Optional type hint in the funcs parameter is no longer issued.
Is this expected behavior?
Yes, the linter is (was) correct. A type has to be fully compatible otherwise there could be potential errors, the linter is right in warning you. In the stricter sense PyCharm should have issued a warning also in the first case because of the potential incompatibility between str and int.
Lets use the Mypy static type checker because its results are in general more accurate.
The following:
def funcs(foo: Optional[str] = None):
    pass
def funci(var: Optional[int] = None):
    funcs(var)
would cause Mypy to issue an error:
your_module.py: error: Argument 1 to "funcs" has incompatible type "Optional[int]"; expected "Optional[str]"
If yes, what can I do about it?
Python uses gradual typing meaning as the code goes along the types can be inspected and thus gradually hinted for correctness.
If you check the type explicitly:
def funci(var: Optional[int] = None):
    if var is None:
        funcs(var)
The Mypy static type checker issues no error. An alternative would also be using cast if you were certain the value would be restricted to None before the line calling funcs(var).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With