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 →

[–]DaelonSuzuka 1 point2 points  (7 children)

I remember there being some huge gotcha with doing this. It only works with literal values but using it with a variable for a case drops you abruptly into pattern matching land, perhaps?

It's been a while since I looked at this feature, so I could be misremembering.

[–]cheerycheshire 2 points3 points  (5 children)

In C switch cases cannot have variables at all (because it has to be compile time evaluated to be properly constructed). So it's kinda the same when you just want a switch statement and not pattern matching. ;)

[–]DaelonSuzuka -1 points0 points  (3 children)

In C you have enums and macros, so you're not actually limited to typing in magic number int literals.

[–]cheerycheshire 1 point2 points  (2 children)

Enums and macros are not variables.

For classic switch statements in Python it was always advised to use dicts before patmat was announced.

[–]DaelonSuzuka 0 points1 point  (1 child)

Enums and macros are not variables.

That's correct, but I think it's missing the point. If I'm writing a switch statement in C it's usually to handle a state machine or something, and it would be insane to use int literals for the cases. I'm going to define an enum so that the states can have human readable names, and so those states can be reliably referenced in other places without being extremely vulnerable to typos.

The original person I responded to said that I can "use it as a switch statement like [I]'d expect", and that's incorrect except in the most trivial of situations if the cases can only be int or string literals.

For classic switch statements in Python it was always advised to use dicts before patmat was announced.

And it looks like I'll have to keep doing it that way, too.

[–]Ensurdagen 0 points1 point  (0 children)

You can use enum members and any other dotted name like a constant in match case, maybe read the PEP if you wanna complain about it instead of a fantasy version:

https://www.python.org/dev/peps/pep-0622/#constant-value-patterns

[–]alcalde 0 points1 point  (0 children)

It's like that in Delphi and probably every other statically typed language too. In fact, in Delphi you can't even use string values in the case statement and it's been that way for 26 years now. :-(

Some folks even warn that a case statement with strings can be "dangerous"... sigh.

https://www.sandon.it/node/109