import os
from typing import Optional
_DEFAULT = 'abc'
def _get_value(param: Optional[str]) -> str:
return param or os.getenv("PARAM", _DEFAULT)
For this function, mypy would complain
Incompatible return value type (got "Optional[str]", expected "str")
but I thought this function will never return None. Am I missing something?
The mypy type checker doesn't seem to be able to parse or conditions. You have to explicitly check for None values:
if param:
return param
else:
return os.getenv("PARAM", _DEFAULT)
Edit: The above code technically checks for falsy values instead of None but it is functionally equivalent to your example.
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