-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Can we have a nicer match
syntax?
#4
Comments
I guess if you implement a global stack to enable |
looking back on this, this could also work, without any global stack: with match(myobj) as M:
with M.case(MyClass.MyConstructor) as x:
return x.y
with M.case(MyClass.MyOtherConstructor) as x:
return x.z |
Actually, I don't think this is possible, because I don't think context managers have any way to stop their code block from being run. |
unless you commit crimes like what this PR for |
Hey hey hey, I'm pround of the atrocities I've commited in that PR, but I wouldn't recomend it though. My use of the I've been thinking of some other ideas though. If we're assuming python 3.8 or higher than something like this could be an option. with object:
if case(case_a_value := object.case_a):
...
if case(case_b_value := object.case_b):
...
if case(x := object.case_c):
case_c_1, case_c_2 = x
... You'll still need to unpack multiple values inside the if because the walrus operator does not support unpacking (case c). I don't think you would need a global stack, the context manager would put the object in a state where it would track access to the cases by using the descriptor protocol. I think your solution with the decorator is the nicest looking, reliable and backwards compatible option I've seen so far. Do you mind if I experiment with it at Edit: Removed the |
Maybe important to add. The |
@aarondewindt Yes, you can of course feel free to take any ideas (or code) you want from sumtypes. I would honestly be happy to just deprecate sumtypes if adt can already do everything that sumtypes does. One of the most annoying things I see with the decorator approach is that it's not really a match expression, it's a way of defining functions whose bodies are entirely match statements. So it's not that great for inline expressions, and also not great for one-off matches in the context of a larger function. Granted, the The other most annoying thing about it is that using I guess it could also be possible to define a decorator which returns the result of immediately evaluating the cases.... but that would read very wierdly: value = Enum.CaseA(1)
@match_immediate(value)
class foo_result:
def CaseA(x): return x
def CaseB(x, y): return y
assert foo_result == 1 yuck. |
How about:
I think I could implement this, but I'm not sure how I would implement exhaustiveness checking.
The text was updated successfully, but these errors were encountered: