0

我有一个 Python 函数用作运行时检查,以确保对象是元组中至少一个类的实例。它有效,我的类型检查器(pyright)正确地从参数推断返回类型:

from typing import Union, Type, Tuple, Any, TypeVar

T = TypeVar('T')

def inst(obj: Any, type: Union[Type[T], Tuple[Type[T], ...]]) -> T:
    if isinstance(obj, type):
        return obj
    raise Exception(f'{obj} must be an instance of {type}')

x = inst(3, (int, str))  # => pyright correctly says x is `int | str`

但是,当我尝试将模式Union[Type[T], Tuple[T, ...]]分解为类型别名时,它会破坏类型推断:

from typing import Union, Type, Tuple, Any, TypeVar

T = TypeVar('T')
TypeOrTupleOfTypes = Union[T, Tuple[T, ...]]

def inst(obj: Any, type: TypeOrTupleOfTypes[Type[T]]) -> T:
    if isinstance(obj, type):
        return obj
    raise Exception(f'{obj} must be an instance of {type}')

x = inst(3, (int, str))  # => pyright now thinks x is `tuple[Type[int], Type[str]]`

为什么我不能在这里使用类型别名?

4

0 回答 0