小编zap*_*zap的帖子

python 中类型变量和类型联合不兼容吗?

考虑以下片段:

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 …

python type-hinting type-variables pyright

6
推荐指数
1
解决办法
264
查看次数

标签 统计

pyright ×1

python ×1

type-hinting ×1

type-variables ×1