DEV Community

Konstantinos Blatsoukas
Konstantinos Blatsoukas

Posted on

python daily #1 (pattern matching)

don't try to match a constant (there will be a match, but not what you would expect)

example:

ERROR = "error"
SUCCESS = "success"

error_obj = {"bar_status": "error"}

match error_obj:
    case {"bar_status": ERROR}:
        print(f"error status matched! status: {ERROR}")
    case _:
        print("No match found")
Enter fullscreen mode Exit fullscreen mode

if you execute the above code, the output will be:

error status matched! status: error
Enter fullscreen mode Exit fullscreen mode

this was my intention, seems that works as expected (but wait for the next one...)

ERROR = "error"
SUCCESS = "success"

error_obj = {"bar_status": "error"}

match error_obj:
    case {"bar_status": SUCCESS}:
        print(f"error status matched! status: {SUCCESS}")
    case _:
        print("No match found")

print(f"SUCCESS status: {SUCCESS}")
Enter fullscreen mode Exit fullscreen mode

output:

error status matched! status: error
SUCCESS status: error
Enter fullscreen mode Exit fullscreen mode

again the same output! what happened?

According to PEP 636 the SUCCESS will be interpreted as a capture pattern. Which means, that is going to match any value, that "bar_status" key has, and use it as a SUCCESS variable (also the SUCCESS variable has now the value error).

The solution for matching constants is to use enums.

The above match could be written as:

class Status(enum.StrEnum):
    ERROR = "error"
    SUCCESS = "success"


error_obj = {"bar_status": "success"}

match error_obj:
    case {"bar_status": Status.ERROR}:
        print(f"error status matched! status: {Status.ERROR}")
    case {"bar_status": Status.SUCCESS}:
        print(f"success status matched! status: {Status.SUCCESS}")
    case _:
        print("No match found")
Enter fullscreen mode Exit fullscreen mode

Cheers!

Top comments (0)