I am using mypy
for linting and I am getting the following error:
Incompatible types in assignment (expression has type "str", variable has type "list[str]")
.
Full Code:
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"
The offending lines are:
app_version = ".".join(app_version[1:])
app_version = ".".join(app_version[:distro_index])
Unfortunately, I can’t disable mypy
. Is there a workaround for this?
You’re getting the error because you initially declare app_version
as a list of strings, and then assign a string to it. This is the kind of thing that can easily lead to a confusing bug where you lose track of what type the variable has at different parts of the function, and end up with a runtime error. The reason you use mypy is to avoid stumbling into exactly this type of mistake.
An easy fix would be to eliminate the superfluous re-assignment before you return the final value:
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"
This way app_version
is always a list[str]
no matter what part of the function you’re looking at.
1