我正在嘗試使用工廠函數來生成一些類型注釋——專門針對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中,文檔字符串中提到了一些對其使用的限制——但這不是其中之一。有什么明顯的我遺漏了嗎?我試圖以這種方式使用這個注釋是不切實際的嗎?我還能嘗試什么?
添加回答
舉報
0/150
提交
取消