lean-python-org / blog

OLD When of Python Blog
https://lean.python.nz/blog
2 stars 0 forks source link

blog/simple-switch-statement-for-python #10

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

Match Case - A Simple Switch Statement for Python? | The When of Python Blog

At first glance, match case (Structural Pattern Matching) looks like a simple switch statement for Python. Unfortunately, match case is a mini-language that is unsafe to use apart from the very narrow cases where its benefits outweigh its costs / risks.

https://when-of-python.github.io/blog/simple-switch-statement-for-python.html

grantps commented 2 years ago

Here's a comment from Robert Collins from the NZPUG mailing list discussion added here with his permission:

"I think all your critiques were raised during the PEP process.

structural matching is an incredibly powerful technique for writing concise, elegant code. In other languages than Python it acts as a zero-cost abstraction; I'm not sure that that aspect got into the design, but then one doesn't pick Python for execution performance but rather expressiveness. And on that basis, yes, I think structural should be in the toolkit for developers and everyone learning current Python should learn it - at least enough to recognise it when they see it.

The really sad thing is that Python has destructuring already in function parameters and name bindings, but only for a small set of types. Extending the destructuring protocol to more places was considered but discarded as too much to bite off in iteration, from memory.

I expect to see destructuring available in more contexts eventually.

-Rob"

grantps commented 2 years ago

I saw a recent tweet on match case a.k.a. Structural Pattern Matching https://twitter.com/reuvenmlerner/status/1576515095047593985

My conclusion: It's smarter than C's switch-case, and has many interesting features and ideas. It's worth knowing.

But when would I use it? I'm not totally sure.

He's not alone in wondering that. There are cases where Structural Pattern Matching is a good solution in Python e.g. working with ASTs or deeply nested JSON, but beyond that it is possibly more trouble than it's worth. A "When of Python" for this feature would be especially useful I think.

grantps commented 9 months ago

I recently encountered another example of match-case being useful from someone I respected - before I opened the article I thought "it's going to JSON because that's basically one of the very few use cases in Python where it is worth the grief" - and so it was: https://nedbatchelder.com/blog/202312/realworld_matchcase.html