This example is being discussed as likely "gotcha" when using pattern matching:
NOT_FOUND = 400
retcode = 200
match retcode:
case NOT_FOUND:
print('not found')
print(f'Current value of {NOT_FOUND=}')
This is an example of accidental capture with structural pattern matching. It gives this unexpected output:
not found
Current value of NOT_FOUND=200
This same problem comes up in other guises:
match x:
case int():
pass
case float() | Decimal():
x = round(x)
case str:
x = int(x)
In this example, str
needs to have parentheses, str()
. Without them, it "captures" and the str builtin type is replaced with the value of x.
Is there a defensive programming practice that can help avoid these problems and provide early detection?