python - 为什么当 Enum 值不匹配时,这个 Python 函数不会抛出错误?

标签 python enums

如果我有一个定义了以下 color arg 的 python 函数:

def search(
    self,
    color: ColorEnum = None
) -> Result:

ColorEnum 看起来像这样:

class ColorEnum(str, Enum):
    Red = "red",
    Green = "green",
    Blue = "blue"

为什么当我执行以下操作时 Python 不会抛出错误:

search(color="black")

Enum 值仅在编译时使用吗?运行时似乎没有任何影响,函数会起作用

最佳答案

函数注释只是您可以附加到函数参数和返回类型的“注释”。尽管您可以访问它们,但它们在运行时没有任何作用。

>>> def foo(x: int) -> str: pass
...
>>> foo.__annotations__
{'x': <class 'int'>, 'return': <class 'str'>}

如果您选择,您可以使用它们来实现您自己的类型检查代码:

def foo(x: int) -> str:
    if not isinstance(x, foo.__annotations__('x')):
        raise ValueError("x is not the right type")
    rv = str(x)
    if not isinstance(rv, foo.__annotations__('return')):
        raise ValueError("wrong return type")
    return rv

当然,这很容易被击败,并且很可能会引入错误,也可能会捕获错误。

类型提示提供文档(“您应该传递一个int作为参数,并且您应该返回一个str value.") 以及静态类型检查器捕获明显错误的方法。给出清晰的定义

def foo(x: int) -> str:
    return str(x)

mypy 这样的工具可以将如下代码标记为错误,而无需执行代码:

foo("nine")  # "nine" does not have type int
3 + foo(5)   # foo returns a str, but you can't add int and str values

关于python - 为什么当 Enum 值不匹配时,这个 Python 函数不会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61636238/

相关文章:

python - 使用pyserial与调制解调器通信

python - 如何使用不同范围的数据框组绘制饼图?

swift - 使用 Enum 和 Struct 进行静态和动态截面建模 - Swift 4

java:将枚举注入(inject)应用程序范围

python - 在 Cython 的结构中使用指针数组

python - 如何设置grequests超时

python - 在非空行上过滤数据框

ios - 如何使用 ObjectMapper 将自定义 Enum/RawRepresentable 映射到字典?

ios - Swift 中的开关 - 开关中的 Case 标签应该至少有一个可执行语句

C++ 构造要求一个未在 .h 中定义的结构