首页 > 解决方案 > MyPy - 赋值中不兼容的类型(表达式的类型为 None,变量的类型为 X)

问题描述

有谁知道为什么 MyPy 抱怨这个?这是非常令人沮丧的,因为如果它是三元的,但如果在标准的 if/else 中,它就不起作用:

from typing import List, Optional, Union

def get_relevant_params() -> List[str]:
    return sorted(list(set(['1', '2', '3'])))

# also doesn't work with: ... -> Union[List[str], None]
def get_config(config_path: Optional[str] = None) -> Optional[List[str]]:
    
    # this doesn't work
    if config_path:
        read_cols = get_relevant_params()
    else:
        read_cols = None
        
    # # this works
    # read_cols = get_relevant_params() if config_path else None

    return read_cols

这是一个带有示例的交互式 MyPy 游乐场: https ://mypy-play.net/?mypy=latest&python=3.8&gist=2c846e569ecbd5f8884367393a754adc

标签: pythonpython-3.xmypypython-typingtyping

解决方案


将第 11 行更改为:

 read_cols: Optional[List[str]] = get_relevant_params()

您的问题是 mypy 将变量的类型read_cols自动识别为 List[str] 因为那是get_relevant_params. 然后,当您尝试将 None 分配给它时,它会显示“不兼容的类型”。如果您在创建变量时指定您希望它是可选的,那么一切正常。


也许更清洁的解决方案是避免使用返回变量。

    if config_path:
        return get_relevant_params()
    else:
        return None

这样,就不会对config_path.


推荐阅读