我使用
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
。有解决方法吗?
您收到错误是因为您最初将
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"