我正在尝试使用工厂函数来生成一些类型注释——专门针对tuple类型。我有一个可以正常工作的工厂版本(例如,它在 MyPy 中编译、运行和检查都令人满意):
import typing as tx
HomogenousTypeVar = tx.TypeVar('HomogenousTypeVar')
TupleTypeReturnType = tx.Type[tx.Tuple[HomogenousTypeVar, ...]]
def TupleType(length: int,
tuptyp: tx.Type[HomogenousTypeVar] = str) -> TupleTypeReturnType:
""" Create a type annotation for a tuple of a given type and length """
assert length > 0
return tx.Tuple[tuple(tuptyp for idx in range(length))]
...的用法如下:
class Thing(object):
__slots__: TupleType(2) = ('yo', 'dogg')
other_fields: TupleType(4) = ('i', 'heard',
'you', 'like')
# etc, or what have you
……但是,当我尝试添加对typing.ClassVar注释的支持时没有成功,看起来像这样:
import typing as tx
HomogenousTypeVar = tx.TypeVar('HomogenousTypeVar')
TupleTypeReturnType = tx.Union[tx.Type[tx.Tuple[HomogenousTypeVar, ...]],
tx.Type[tx.ClassVar[tx.Tuple[HomogenousTypeVar, ...]]]]
def TupleType(length: int,
tuptyp: tx.Type[HomogenousTypeVar] = str,
clsvar: bool = False) -> TupleTypeReturnType:
""" Create a type annotation for a tuple of a given type and length,
specifying additionally whether or not it is a ClassVar """
assert length > 0
out = tx.Tuple[tuple(tuptyp for idx in range(length))]
return clsvar and tx.ClassVar[out] or out
...在此更改之后,代码甚至不会在最初编译 - 它无法TypeError通过typing模块深处的a 编译:
类型错误:typing.ClassVar[typing.Tuple[~HomogenousTypeVar, ...]] 作为类型参数无效
......随着错误的发生,让我觉得有点打电话; 我的意思是,是不是一切都在typing应该以某种方式,给有或采取有效的类型参数?
在与 相关的typing源代码ClassVar中,文档字符串中提到了一些对其使用的限制——但这不是其中之一。有什么明显的我遗漏了吗?我试图以这种方式使用这个注释是不切实际的吗?我还能尝试什么?
相关分类