News for hackers. Stuff that matters.
Re:Structural pattern matching in Python 3.10 by gigatexal on Monday September 20, 2021 @08:58PM (#28600919)
I used to do this with a dict. Glad this is in Python 3.10.
Re:Structural pattern matching in Python 3.10 by jimminy on Monday September 20, 2021 @09:23PM (#28601075)
Yeah, I think the author focused a bit too much on structural pattern matching being a replacement/alternative for if...elif blocks.

It will be much more useful as an alternative to dispatch dictionaries, which are more a side-effect of the language lacking any case based control-flow.

Re:Structural pattern matching in Python 3.10 by kristjansson on Tuesday September 21, 2021 @12:52AM (#28602134)
Yeah, there are several giant dictionaries (variously class to function, string to class, etc.) in just the project I’ve worked on most recently that fit that description.

Though considered from that perspective, it’s actually a bit of a disadvantage that the new match statement is a part of the language. It’s nice to dynamically extend (either as a first party developer or third party user) that sort of dictionary, effectively adding new branches to the implicit switch statement. A match statement is going to be fixed as written. Probably a readability and consistency win to remove spooky-action-at-a-distance, but at the cost of a bit of (ugly, pragmatic) usability

Re:Structural pattern matching in Python 3.10 by ufo on Tuesday September 21, 2021 @12:27AM (#28602033)
By the way, does anyone here know how Python compiles the match statements under the hood? Are they converted into something equivalent to if-elif, which tries each option in sequence? Or does it do something more clever?
Re:Structural pattern matching in Python 3.10 by mixmastamyk on Tuesday September 21, 2021 @03:58AM (#28602929)
The author replied here that yes, the bytecode is simple, with the exception of the Class matching.

https://news.ycombinator.com/threads?id=benhoyt

Re:Structural pattern matching in Python 3.10 by benhoyt on Monday September 20, 2021 @09:42PM (#28601187)
Do you mean like "f = handlers.get(args.command, error); f(args)"? It's a fine pattern (of course, it's only a tiny fraction of what pattern matching can do). However, it does mean that if the handlers aren't already functions, you have to convert them to (possibly nested) functions, but that can sometimes make the code clearer and easier to test anyway.

But if you're not matching structure I really don't see what's wrong with plain old if...elif? And you can easily add more complex tests like "in" clauses this way too:

  cmd = args.command
  if cmd == 'push':
      # do push
  elif cmd in ['pull', 'pul']:
      # do pull
  else:
      error(f'command {cmd!r} not yet implemented')
Re:Structural pattern matching in Python 3.10 by dehrmann on Monday September 20, 2021 @09:22PM (#28601066)
It took way too long to get this considering how case has been around forever. Now I just want a do-while.