如何对 Python 函数进行类型注释以将其标记为仅在输入为 None 时才返回 None?

How to type-annotate a Python function to mark it as returning None only when the input is None?

在我们的代码中有一个典型的数据转换模式:当值为None时,我们让它通过。例如,

def capitalize(value):  
    if value is None:  
        return None  
    return value.capitalize()
     
# usage example:
assert capitalize(None) is None
assert capitalize("hello world") == "Hello world"

我可以这样标注:

from typing import Optional


def capitalize(value: Optional[str]) -> Optional[str]:  
    if value is None:  
        return None  
    return value.capitalize()

看起来还可以,但是下面的代码

capitalize("Hello world").split()

总是让 mypy 抱怨。

error: Item "None" of "Optional[str]" has no attribute "split"

有没有办法用类型注解表达转换规则“None总是转换成None,str总是转换成str?”

这听起来像是 Generics 的用例,具有值限制。

下面的代码基本上说 T 可以是 strNone,函数定义说“此函数 returns 与出现的类型相同在”。

from typing import TypeVar

T = TypeVar("T", str, None)

def capitalize(value: T) -> T:
    if value is None:
        return None
    return value.capitalize()

capitalize("Hello world").split()

运行 mypy 上面的代码似乎工作正常,并且:

capitalize(None).split()

导致 mypy 抱怨:error: "None" has no attribute "split" 我认为这就是你想要的。