How to use values stored in variables as case patterns?

If the constant you’re testing against is a dotted name, then it should be treated as a constant instead of as the name of the variable to put the capture in (see PEP 636 # Matching against constants and enums):

class Codes:
    SUCCESS = 200
    NOT_FOUND = 404

def handle(retcode):
    match retcode:
        case Codes.SUCCESS:
            print('success')
        case Codes.NOT_FOUND:
            print('not found')
        case _:
            print('unknown')

Although, given how python is trying to implement pattern-matching, I think that for situations like this it’s probably safer and clearer code to just use an if/elif/else tower when checking against constant values.

Leave a Comment