亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號