如何使用打字模块创建自定义类型?

问题描述 投票:0回答:1

我正在尝试在Python 3.7键入模块上创建自定义类型。新类型(例如Struct)应与tuple类型相同。在Python3.6中,我可以通过Typing.GenericMetatyping.TupleMeta执行相同的操作。

[随着在Python3.7中更新了输入模块,GenericMetaTupleMeta不存在,并且我想继承的特殊类是不可能的。例如_VariadicGenericAlias

我真正想要的是类似于:

Struct = _VariadicGenericAlias(tuple, (), , inst=False, special=True)

assert _origin(Struct[int, str]) == Struct

注意:

def _origin(typ: Any) -> Any:
    """Get the original (the bare) typing class.
    Get the unsubscripted version of a type. Supports generic types, Union,
    Callable, and Tuple. Returns None for unsupported types. Examples::
        get_origin(int) == None
        get_origin(ClassVar[int]) == None
        get_origin(Generic) == Generic
        get_origin(Generic[T]) == Generic
        get_origin(Union[T, int]) == Union
        get_origin(List[Tuple[T, T]][int]) == list
    """
    if isinstance(typ, _GenericAlias):
        return typ.__origin__ if typ.__origin__ is not ClassVar else None
    if typ is Generic:
        return Generic
    return None
python python-3.7 python-typing
1个回答
0
投票

找出了对我有用的解决方案。利用了_GenericAlias中隐藏的“名称”参数:

Struct = _VariadicGenericAlias(tuple, (), , inst=False, special=True, name="Struct")
© www.soinside.com 2019 - 2024. All rights reserved.