Python NewType('X', Y): mypy displays error: got Y, expected X

589 Views Asked by At

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?

error

1

There are 1 best solutions below

1
On BEST ANSWER

You need to explicitly create an Offset from your x, y tuple:

def f(x: int, y: int) -> Offset:
    return Offset((x, y))

This is because, from NewType helper function: "type checkers require explicit casts from int where UserId is expected", or in your case: from Tuple[int, int] to Offset.

May just be for your example, but if f really does perform no validation on x and y before returning an Offset, a NewType here is unnecessary. In that case, I would suggest declaring Offset as:

Offset = tau.Tuple[int, int]

which is a type alias.