python-switch icon indicating copy to clipboard operation
python-switch copied to clipboard

Idea: decorator to inline function definitions

Open dschep opened this issue 8 years ago • 1 comments

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 avatar Oct 12 '17 12:10 dschep

@dschep That is a clever use of functools.partial

knowsuchagency avatar Oct 12 '17 18:10 knowsuchagency

Good idea!

zty012 avatar Jan 08 '23 08:01 zty012

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.

mikeckennedy avatar Jan 16 '23 18:01 mikeckennedy