python-switch
python-switch copied to clipboard
Idea: decorator to inline function definitions
I stumbled upon this via Github's new "discover repos" feature, interesting project!
Having s.case capable of working as decorators would allow you to not have to define functions separately from their case. Here's the example from the readme written this way using functools.partial to handle that s.case wasn't meant to be used this way:
from functools import partial
from switchlang import switch
num = 7
val = input("Enter a key. a, b, c or any other: ")
with switch(val) as s:
@partial(s.case, 'a')
def process_a():
print("Found A!")
@partial(s.case, 'b')
def process_with_data():
print("Found with data: {}".format((val, num, 'other values still')))
@s.default
def process_any():
print("Found Default!")
@dschep That is a clever use of functools.partial
Good idea!
Hi @dschep Sorry I somehow missed this idea. It's a very clever suggestion. But I feel it's a bit too much syntax IMO. Every case would come along with two lines of extra boilerplate.
Whereas with the lambdas it's one line per case. If you need something more complex, that encourages (almost forces) use of separating that into functions that are called in the lambda.