I have a Python static typing conundrum. I'd like a solution that works with mypy.
I have a function which fills out a list, albeit not "in order", so it's inconvenient to write it as a list comprehension or similar.
So, I fill the list with [None] and assert that all the Nones are gone by the time it returns.
However, the assertion I wrote does NOT convince mypy that the type of result now matches the return type of f, and I get a diagnostic: Incompatible return value type (got "list[int | None]", expected "list[int]")
def f() -> list[int]:
result: list[int|None] = [None] * 3
result[0] = 1
result[2] = 2
result[1] = 3
assert not any(i is None for i in result)
return result
Any hints? Can I do something besides cast the return value?
Solution: I used TypeGuard (python 3.10+) as suggested in replies. I can accept the runtime overhead.
#askMastodon #python #mypy #answered