I understand that there are no switch cases in python and that a dictionary can be used instead. But what if i want to pass arguments the function zero() but no arguments to one()? I didnt find any question related to this.
def zero(number):
return number == "zero"
def one():
return "one"
def numbers_to_functions_to_strings(argument):
switcher = {
0: zero,
1: one,
2: lambda: "two",
}
# Get the function from switcher dictionary
func = switcher.get(argument, lambda: "nothing")
# Execute the function
return func()
what is the simplest way to implement this without having to separate them into two cases? i think that func() would need to take the (optional) arguments?
You could use partial
from functools import partial
def zero(number):
return number == "zero"
def one():
return "one"
def numbers_to_functions_to_strings(argument):
switcher = {
0: partial(zero, argument),
1: one,
2: lambda: "two",
}
func = switcher.get(argument, lambda: "nothing")
return func()
If I understood the case correctly, here is an alternative take for doing that without importing anything and also without lambda. You can just navigate to the necessary methods you already have outside the switcher:
def fa(num):
return num * 1.1
def fb(num, option=1):
return num * 2.2 * option
def f_default(num):
return num
def switch(case):
return {
"a":fa,
"b":fb,
}.get(case, f_default) # you can pass
print switch("a")(10) # for Python 3 --> print(switchcase("a")(10))
print switch("b")(10, 3) # for Python 3 --> print(switchcase("b")(10, 3))
print(switchcase("a")(10))
11.0
print(switchcase("b")(10, 3))
66.0
print(switchcase("ddd")(10))
10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With