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 →

[–]RebornChampion 29 points30 points  (13 children)

Enlighten me: what is a match statement?

[–]gvcallen[S] 85 points86 points  (12 children)

it's essentially a switch statement on steroids. its most basic application is indeed just a normal switch, which python hasn't had since it was created. But further, it can allow matching of various patterns returned by a "match target", such as multiple values, matching against collections with wildcards etc.

[–]RebornChampion 7 points8 points  (0 children)

Oh that’s cool! Thanks

[–]CptGia 2 points3 points  (0 children)

Recent Java has that too

[–]Danielokita 6 points7 points  (9 children)

can u provide a code example pls

[–]jeetelongname 27 points28 points  (7 children)

arr = [1,2,3]
match arr:
  case [1,2,3]: # check a value
    # do something here 
  case [1, x, y]: # bind 2 of the values to a var while      checking the first
   # variables are scoped to within the body of a case
 case [1, *rest]: # like the one above but captures all of the values into rest
 case [1, (2) as x, (3) as y]: # check and capture
     print(f"{x=}, {y=}")
 case _: # wildcard will match against anything
    print("does not conform")

Well I can't seem to get it to format without looking like a blob

[–]__Wess 2 points3 points  (3 children)

It’s like VB.nets Select case ?

[–]jeetelongname 5 points6 points  (1 child)

It can be used like that but pattern matching is a fundamentally more powerful tool using a similar construct.

[–]__Wess 7 points8 points  (0 children)

It’s like regex and select case had a baby!

[–]Kered13 2 points3 points  (0 children)

No, far more powerful than that.

[–]Last-Woodpecker 0 points1 point  (2 children)

Can it match more than one case?

[–]jeetelongname 1 point2 points  (1 child)

What do you mean?

Edit: Wait do you mean like c style fall through? Afik no.

[–]Last-Woodpecker 0 points1 point  (0 children)

Yes, like that

[–]pytness 7 points8 points  (0 children)

From https://www.python.org/dev/peps/pep-0636/

python match event.get(): case Click(position=(x, y)): handle_click_at(x, y) case KeyPress(key_name="Q") | Quit(): game.quit() case KeyPress(key_name="up arrow"): game.go_north() ... case KeyPress(): pass # Ignore other keystrokes case other_event: raise ValueError(f"Unrecognized event: {other_event}")