Neil G
Neil G

Reputation: 33192

How can I use nominal typing with mypy?

This isn't my exact use case, but it's similar. Suppose I want to define two typing annotations:

Matrix = np.ndarray
Vector = np.ndarray

Now, I want a potential type-checker to complain when I pass a Matrix to a function that accepts a Vector:

def f(x: Vector):
    ...

m: Matrix = ...
f(m)  # Bad!

How do I mark these types as incompatible?

Upvotes: 2

Views: 652

Answers (1)

Neil G
Neil G

Reputation: 33192

It appears that I can use typing.NewType to create distinct types:

from typing import NewType


A = NewType('A', int)
B = NewType('B', int)

def f(a: A):
    pass

b: B
f(b)

gives

a.py:11: error: Argument 1 to "f" has incompatible type "B"; expected "A"

Unfortunately, it doesn't work with np.ndarray until either numpy implements type hinting or NewType supports a base type of Any.

Upvotes: 3

Related Questions