在Union上分配的类型不兼容

问题描述 投票:1回答:1

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.")
python python-3.x types python-3.5 mypy
1个回答
3
投票

避免这个问题的正确方法是使用@overload装饰器来描述函数参数与其结果之间的关系。

函数get()将返回str(实际上是Optional[str],因为它也可能返回None)如果它传递了str并且它将返回字典,如果它通过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]'

在将来,我还建议您在发布之前花几分钟来简化您的示例,以便其他人可以重现。

© www.soinside.com 2019 - 2024. All rights reserved.