I want to use a type checker that helps me writing good code and I think mypy does what I want. But I do not get how to write the following code.
import typing as tau
Offset = tau.NewType('Offset', tau.Tuple[int, int])
def f(x: int, y: int) -> Offset:
return x, y
important_for_me = Offset != tau.Tuple[int, int]
assert important_for_me
For a framework I am writing it is important to not just assign an identifier to a type, but I still want the typechecker to know how to help me (so not just assign TypeVar and lose information).
typing.NewType works perfectly fine, but mypy gives me an error at line 7:
Incompatible return value type (got "Tuple[int, int]", expected "Offset")
Is there a way how to write it exactly like I did but in a way that the typechecker understands it?
You need to explicitly create an
Offset
from yourx, y
tuple:This is because, from NewType helper function: "type checkers require explicit casts from
int
whereUserId
is expected", or in your case: fromTuple[int, int]
toOffset
.May just be for your example, but if
f
really does perform no validation onx
andy
before returning anOffset
, aNewType
here is unnecessary. In that case, I would suggest declaringOffset
as:which is a type alias.