简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM