1
+ x ,y = 5 ,3
2
+ op = "add"
3
+
4
+ if op == "add" :
5
+ print (x + y )
6
+ elif op == "mul" :
7
+ print (x * y )
8
+
9
+ match op :
10
+ case "add" :
11
+ print (x + y )
12
+ case "mul" :
13
+ print (x * y )
14
+
15
+ #Good alternative
16
+ functions = {
17
+ "add" : lambda x ,y : x + y ,
18
+ "mul" : lambda x ,y : x * y
19
+ }
20
+
21
+ print (functions ["add" ](5 ,3 ))
22
+
23
+ #using proper functions
24
+ def add (x ,y ):
25
+ return x + y
26
+ def mul (x ,y ):
27
+ return x * y
28
+
29
+ functions = {
30
+ "add" :add ,
31
+ "mul" :mul ,
32
+ }
33
+
34
+ print (functions ["mul" ](5 ,3 ))
35
+
36
+ #emulating match/case pattern
37
+ from collections import defaultdict
38
+
39
+ cases = defaultdict (lambda * args : lambda * a : "Invalid option" ,{
40
+ "add" :add ,
41
+ "mul" :mul ,
42
+ })
43
+
44
+ print (cases ["add" ](5 ,3 ))
45
+ #passing parameters
46
+ def handle_event (e ):
47
+ print (f"Handling event in 'handler_event' with { e } " )
48
+ return e
49
+
50
+ def handle_other_event (e ):
51
+ print (f"Handling event in 'handle_other_event' with { e } " )
52
+ return e
53
+
54
+ functions = {
55
+ "event1" : lambda arg : handle_event (arg ["some_key" ]),
56
+ "event2" : lambda arg : handle_other_event (arg ["some_other_key" ]),
57
+ }
58
+
59
+ event = {
60
+ "some_key" :"value" ,
61
+ "some_other_key" :"different value" ,
62
+ }
63
+
64
+ print (functions ["event1" ](event ))
65
+ print (functions ["event2" ](event ))
66
+
67
+ #Real world code call it [parse_args.py]
68
+ import argparse
69
+
70
+ functions = {
71
+ "add" :add ,
72
+ "mul" :mul ,
73
+ }
74
+
75
+ parser = argparse .ArgumentParser ()
76
+ parser .add_argument (
77
+ "operation" ,
78
+ choices = ["add" ,"mul" ],
79
+ help = "operation to perform (add,mul)" ,
80
+ )
81
+
82
+ parser .add_argument (
83
+ "x" ,
84
+ type = int ,
85
+ help = "first number"
86
+ )
87
+
88
+ parser .add_argument (
89
+ "y" ,
90
+ type = int ,
91
+ help = "second number" ,
92
+ )
93
+
94
+ args = parser .parse_args ()
95
+ answer = functions .get (args .operation ,)(args .x ,args .y )
96
+ print (answer )
0 commit comments