What you're asking for is impossible (see below for explanation). But usually, there's no need in python to require that two arguments have precisely identical type.
In your example, int
, str
, List[int]
, Callable[[], int]
don't have any common methods or attributes (other than what any two object
instances have), so unless you manually check the type with isinstance
, you can't really do anything with your argument that you couldn't do with object
instances. Could you explain your use case?
Explanation of why you can't enforce type equality
Mypy type system has subtyping. So when you write f(a, b)
, mypy only checks that types of a
and b
are both subtypes of T
rather than precisely equal to T
.
In addition mypy subtyping system is mostly pre-defined and not under the programmer control, in particular every type is a subtype of object
. (IIUC, in OCaml the programmer needs to say explicitly which types should be in a subtyping relationship, so by default every type constraint is equality constraint. That's why you could do what you wanted in OCaml).
So, when you write
T = TypeVar('T')
f(a: T, b: T) -> None: ...
f(x, y)
you are only telling mypy that the types of x
and y
must be subtypes of some common type T
. And of course, this constraint is always (trivially) satisfied by inferring that T
is object
.
Update
To your question in the comment (is it possible to ensure that type of y
is of subtype of type of x
?), the answer is also no.
Even though mypy
allows a type variable to be bounded from above by a specified type, that bound cannot be another type variable, so this won't work:
T = TypeVar('T')
U = TypeVar('U', bound=T, contravariant=True) # error, T not valid here
f(x: T, y: U) -> None
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…