为了账号安全,请及时绑定邮箱和手机立即绑定

在 Python 3.7 中使用工厂函数生成注释类型时“typing.ClassVar”的问题

在 Python 3.7 中使用工厂函数生成注释类型时“typing.ClassVar”的问题

狐的传说 2021-06-07 12:43:47
我正在尝试使用工厂函数来生成一些类型注释——专门针对tuple类型。我有一个可以正常工作的工厂版本(例如,它在 MyPy 中编译、运行和检查都令人满意):import typing as txHomogenousTypeVar = 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 txHomogenousTypeVar = 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中,文档字符串中提到了一些对其使用的限制——但这不是其中之一。有什么明显的我遗漏了吗?我试图以这种方式使用这个注释是不切实际的吗?我还能尝试什么?
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号