mypy 错误:赋值中的类型不兼容(表达式的类型为“str”,变量的类型为“list[str]”)

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

我使用

mypy
进行 linting,但出现以下错误:
Incompatible types in assignment (expression has type "str", variable has type "list[str]")

完整代码:

def extract_version(path: str, distro: str) -> str:
    with open(path, 'r') as f:
        version_info = f.readline().strip().split("-")
        app_version = version_info[-1].split("_")

    if distro not in app_version:
        app_version = ".".join(app_version[1:])
        return app_version
    elif distro == app_version[0]:
        return "Unknown"
    elif distro in app_version:
        app_version.pop(0)
        distro_index = app_version.index(distro)
        app_version = ".".join(app_version[:distro_index])
        return app_version
        
    return "Unknown"

违规行是:

app_version = ".".join(app_version[1:])

app_version = ".".join(app_version[:distro_index])

不幸的是,我无法禁用

mypy
。有解决方法吗?

python python-3.x mypy
1个回答
0
投票

您收到错误是因为您最初将

app_version
声明为字符串列表,然后为其分配一个字符串。一个简单的解决方法是在返回最终值之前消除多余的重新分配:

def extract_version(path: str, distro: str) -> str:
    with open(path, 'r') as f:
        version_info = f.readline().strip().split("-")
        app_version = version_info[-1].split("_")

    if distro not in app_version:
        return ".".join(app_version[1:])
    elif distro == app_version[0]:
        return "Unknown"
    elif distro in app_version:
        app_version.pop(0)
        distro_index = app_version.index(distro)
        return ".".join(app_version[:distro_index])
    else:      
        return "Unknown"
© www.soinside.com 2019 - 2024. All rights reserved.