考虑以下片段:
from typing import TypeVar
import numpy as np
T = TypeVar("T", float, np.ndarray)
def f(x: T) -> T:
"""
expects a float or an array and returns an output of the same type
"""
return x * 2
f(1) # ok
f(np.array([1, 2, 3])) # ok
def g(x: float | np.ndarray) -> float | np.ndarray:
"""
expects either a float or an array
"""
return f(x) / 2 # should be fine, but pyright complains about type
Run Code Online (Sandbox Code Playgroud)
我创建了一个 TypeVar …