t-m*_*art 9 python enums type-hinting mypy
我已经enum.Enum与几个成员一起编写了一个类型。现在我想编写一个“选择器” ,它将返回基于参数@classmethod的成员之一,但我不知道如何正确输入提示。Enum
这是我到目前为止所要做的:
from enum import Enum, auto
from typing import TypeVar, Type
_StringSizeT = TypeVar("_StringSizeT", bound="StringSize")
class StringSize(Enum):
SMALL = auto()
BIG = auto()
@classmethod
def from_string(cls: Type[_StringSizeT], source_string: str) -> _StringSizeT:
n_chars = len(source_string)
if n_chars <= 10:
return cls.SMALL
return cls.BIG
Run Code Online (Sandbox Code Playgroud)
上面使用TypeVar()等 是我尝试遵循Martijn Pieters 在“当值是 cls 实例时可以注释返回类型吗?”中的帖子的方法。对于@classmethod工厂,但将它们应用于Enum @classmethod返回枚举成员之一的 s。
不幸的是,mypy 不喜欢我的 return 语句的类型:
error: Incompatible return value type (got "StringSize", expected "_StringSizeT")
Run Code Online (Sandbox Code Playgroud)
这是因为它的属性@classmethod与那篇文章中的不同:我没有返回类的实例,而是返回类属性,或者用枚举来说,返回一个成员。
我如何在这里修复我的方法注释?
更新:好的,在写这篇文章时,我重复了 mypy 的建议,发现
error: Incompatible return value type (got "StringSize", expected "_StringSizeT")
Run Code Online (Sandbox Code Playgroud)
是可以接受的。这有点令人困惑,因为我再次没有返回实例,但我将其归因于下面的元编程机制Enum。后续:是否有我可以在这里使用的非字符串文字类型注释?根据我的经验,我学会了(也许是错误的)不喜欢字符串文字注释。(我有没有为他们牺牲什么?)