如果我有一个定义了以下 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/