【发布时间】:2021-08-04 03:17:13
【问题描述】:
This example 在使用模式匹配时被认为可能是“陷阱”:
NOT_FOUND = 400
retcode = 200
match retcode:
case NOT_FOUND:
print('not found')
print(f'Current value of {NOT_FOUND=}')
这是使用结构模式匹配意外捕获的示例。它给出了这个意想不到的输出:
not found
Current value of NOT_FOUND=200
同样的问题以其他形式出现:
match x:
case int():
pass
case float() | Decimal():
x = round(x)
case str:
x = int(x)
在本例中,str 需要有括号,str()。没有它们,它会“捕获”并且 str 内置类型被替换为 x 的值。
是否有defensive programming 实践可以帮助避免这些问题并提供早期检测?
【问题讨论】:
标签: python defensive-programming python-3.10 structural-pattern-matching