Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mypy complains Incompatible return value type (got "Optional[str]", expected "str") when a function can only return str

Tags:

python

mypy

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?

like image 405
zyxue Avatar asked Oct 26 '25 06:10

zyxue


1 Answers

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.

like image 111
Selcuk Avatar answered Oct 29 '25 08:10

Selcuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!