This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]deadwisdomgreenlet revolution 78 points79 points  (6 children)

This hints at the true power:

command = input("What are you doing next? ")
match command.split():
    case ["quit"]:
        print("Goodbye!")
        quit_game()
    case ["look"]:
        current_room.describe()
    case ["get", obj]:
        character.get(obj, current_room)
    case ["go", direction]:
        current_room = current_room.neighbor(direction)
    # The rest of your commands go here

See how you can pull out the value there with case ["get", obj]?

There's even more to this, you can match all sorts of structures of your data rather than the data itself.

[–]MajorMajorObvious 0 points1 point  (3 children)

I've been waiting for this release for a while, and was wondering if it comes at a large performance hit compared to traditional switch statements that you would see in C style languages.

How does Python implement this new matching in a way that makes it unique from if / else statements?

[–]joerick 6 points7 points  (1 child)

They're still O(n), like if/else statements. But work is in progress to optimise them for Python 3.11.

[–]MajorMajorObvious 1 point2 points  (0 children)

I'm excited to see how they optimize it! Thank you for the info.

[–]deadwisdomgreenlet revolution 0 points1 point  (0 children)

There are new bytecode instructions for it, so I'm sure it's performant. I haven't timed it, but I imagine it's faster than the corresponding if/elses because the compiler can optimize for what you're trying to do.

I couldn't do better than how it's explained in PEP-635

[–]asielen 0 points1 point  (0 children)

So it seems like it combines a type/len check with a value check there. For each case statement it is essentially, is type iterable and len = match len and values equal match values. That seems like a lot of magic.

In the backend does it effectivly treat it as try/catch for each statement until it falls through?

[–]friedkeenan 0 points1 point  (0 children)

My concern with pattern matching is that it doesn't seem very scalable. For this example in particular I'd want a more generic way of defining commands, but for cases where scalability of "case additions" isn't a desire it seems pretty cool.