UNION上赋值中的不兼容类型

2022-04-18 00:00:00 python python-3.x python-3.5 types mypy

问题描述

Mypy给我打印以下消息:

X.py:74:错误:赋值中的类型不兼容(表达式具有类型 "Union[str,dict[str,str]]",变量的类型为"str")

这不奇怪吗?strUnion[str, Dict[str, str]]的一部分

代码如下:

def get_multiple(fields: List[str], config_data) -> Dict[str, str]:
    config_results = {k: v for k, v in config_data.items() if k in fields}
    log_missing_fields(fields, config_results)
    return config_results


def get_single(field: List[str], config_data) -> str:
    result = config_data.get(field)
    if result is None:
        log.warning('The following fields are missing: %s', field)
    return result


def get(fields: Union[str, List[str]]) -> Union[str, Dict[str, str]]:
    log.debug('Retrieving values %s from config', str(fields))
    config_data = read_config()
    get_data = get_multiple if isinstance(fields, list) else get_single
    return get_data(fields, config_data)


def get_ts_url() -> str:
    timeout = get('timeout')  # type: str <-- Line 74 is here
    log.info('Trying to connect the servers.')
    with db_session() as db_handler:
        url = scan_availability(db_handler, int(timeout))

    if url:
        return url

    log.critical("Could not find available servers.")
    raise ConnectionError("Could not find available servers.")

解决方案

避免此问题的正确方法是使用@overload修饰符来描述函数的参数及其结果之间的关系。

如果函数get()传递给str,它将返回str(实际上是Optional[str],因为它也可能返回None),如果传递list,它将返回一个词典。下面是我们如何使用类型注释来描述:

from typing import *


def read_config() -> Dict[str, str]:
    return {}


def get_multiple(fields: List[str], config_data: Dict[str, str]) -> Dict[str, str]:
    config_results = {k: v for k, v in config_data.items() if k in fields}
    return config_results


def get_single(field: List[str], config_data: Dict[str, str]) -> Optional[str]:
    result = config_data.get(field)
    return result


@overload
def get(fields: str) -> Optional[str]: ...

@overload
def get(fields: List[str]) -> Dict[str, str]: ...

def get(fields):
    config_data = read_config()
    get_data = get_multiple if isinstance(fields, list) else get_single
    return get_data(fields, config_data)


def get_ts_url() -> None:
    timeout = get('timeout')
    if TYPE_CHECKING:
        reveal_type(timeout)

如果您对此运行mypy,它将打印

Revealed type is 'Union[builtins.str, builtins.None]'

以后,我还建议在发帖前花几分钟时间来简化您的示例,以便其他人也可以复制它。

相关文章