Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python switch case allowing optional arguments

Tags:

python

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?

like image 476
user3710760 Avatar asked Dec 04 '22 01:12

user3710760


2 Answers

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()
like image 124
Pedru Avatar answered Dec 21 '22 23:12

Pedru


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

like image 42
nrp Avatar answered Dec 22 '22 01:12

nrp