Returning Any from function declared to return "str" while returning a Dict val

Viewed 361

I have a function that reads a version.py and returns the version val. The function looks like this:

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"]

The version.py script looks like this:

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

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

The type for VERSION["VERSION"] is an str. However, I keep getting the error: Returning Any from function declared to return "str"

How do I make it realize that the type is an str and not Any?

1 Answers

You have declared VERSION to be a generic dictionary, something that could contain any type of value. If you change your annotation to be more specifc, like VERSION: Dict[str, str] = {}, mypy will understand that what you are returning is a string, because your dictionary is defined as only holding string values.

Related