返回任何声明为返回“str”的函数,同时返回 Dict val

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

我有一个函数可以读取

version.py
并返回版本 val。该函数如下所示:

def write_ini() -> str:
    """Write version.ini file by extracting version from version.py."""
    # get root dirname
    filepath = realpath(__file__)
    root = dirname(dirname(dirname(filepath)))
    VERSION: Dict = {}

    # Extract version from version.py
    with open(op.join(root, "package_folder", "version.py"), encoding="utf8") as version_file:
        exec(version_file.read(), VERSION)
    print(VERSION["VERSION"])
    config["VERSION"] = {"cv_version": "v{}".format(VERSION["VERSION"])}

    # write to version.ini
    with open("version.ini", "w") as configfile:
        config.write(configfile)

    return VERSION["VERSION"]

version.py
脚本看起来像这样:

_MAJOR = "1"
_MINOR = "0"
_REVISION = "13"

VERSION_SHORT = f"{_MAJOR}.{_MINOR}"
VERSION = f"{_MAJOR}.{_MINOR}.{_REVISION}"

VERSION["VERSION"]
的类型是
str
。但是,我不断收到错误:
Returning Any from function declared to return "str"

我如何让它意识到该类型是

str
而不是
Any

python python-typing mypy
1个回答
2
投票

您已将 VERSION 声明为通用字典,可以包含任何类型的值。如果您将注释更改为更具体,例如

VERSION: Dict[str, str] = {}
,mypy 会理解你返回的是一个字符串,因为你的字典被定义为只保存字符串值。

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