structural-pattern-matching

How to perform approximate structural pattern matching for floats and complex

How to perform approximate structural pattern matching for floats and complex Question: I’ve read about and understand floating point round-off issues such as: >>> sum([0.1] * 10) == 1.0 False >>> 1.1 + 2.2 == 3.3 False >>> sin(radians(45)) == sqrt(2) / 2 False I also know how to work around these issues with math.isclose() …

Total answers: 2

Structural pattern matching using regex

Structural pattern matching using regex Question: I have a string that I’m trying to validate against a few regex patterns and I was hoping since Pattern matching is available in 3.10, I might be able to use that instead of creating an if-else block. Consider a string ‘validateString’ with possible values 1021102,1.25.32, string021. The code …

Total answers: 4

Capture makes remaining patterns unreachable

Capture makes remaining patterns unreachable Question: Why does this code fail: OKAY = 200 NOT_FOUND = 404 INTERNAL_SERVER_ERROR = 500 match status: case OKAY: print(‘It worked’) case NOT_FOUND: print(‘Unknown’) case INTERNAL_SERVER_ERROR: print(‘Out of service’) case _: print(‘Unknown code’) It generates this error message: File "/Users/development/Documents/handler.py", line 66 case OKAY: ^^^^ SyntaxError: name capture ‘OKAY’ makes …

Total answers: 2

How to use values stored in variables as case patterns?

How to use values stored in variables as case patterns? Question: I’m trying to understand the new structural pattern matching syntax in Python 3.10. I understand that it is possible to match on literal values like this: def handle(retcode): match retcode: case 200: print(‘success’) case 404: print(‘not found’) case _: print(‘unknown’) handle(404) # not found …

Total answers: 6