0

just started to mess with python and I'm looking for an alternative for Switch-Case like i had in C#

I have a Menu with 3 options for example. this is the switcher i have right now:

def mySC(i):
    switcher = {
        '1': funcName1,
        '2': funcName2,
        '3': funcName3
    }
    func = switcher.get(i, lambda: 'Invalid')
    return func()

it works and I'm able to enter the function i want. my problem is what if i want to send different arguments to each function? for ex. if someone entered 1 i want it to enter funcName1() but also send a var into it like funcName1(nums) and for 2 i want to send funcName1(myTwoDimList)

how will i be able to do that?

thanks in advance, Amit.

SMortezaSA
  • 589
  • 2
  • 15
AmitHarpaz
  • 23
  • 1
  • 9

3 Answers3

1

You also can add *args (positional) and **kwargs (keyword) arguments to your function:

def mySC(i, *args, **kwargs):
    switcher = {
        '1': funcName1,
        '2': funcName2,
        '3': funcName3
    }
    func = switcher.get(i, lambda *args, **kwargs: 'Invalid')
    return func(*args, **kwargs)
SimfikDuke
  • 943
  • 6
  • 21
0

If the variables you want to pass to your functions are already defined at that point, you can just use partial application. Python has a partial object in it's stdlib, but a mere lambda is enough here:

foo = 42
bar = ["s", "p", "a", "m"]
baaz = {"parrot": "dead"}  

def mySC(i):
    switcher = {
        '1': lambda: func1(foo),
        '2': lambda: func2(bar),
        '3': lambda: func3(baaz)
    }
    func = switcher.get(i, lambda: 'Invalid')
    return func()

If those vars aren't defined when you define your myMC function but are still "fixed" from one call to another (in a same process), you can add a layer of indirection to create the MySC function dynamically:

def create_switch(foo, bar, baaz):
    def mySC(i):
        switcher = {
            '1': lambda: func1(foo),
            '2': lambda: func2(bar),
            '3': lambda: func3(baaz)
        }
        func = switcher.get(i, lambda: 'Invalid')
        return func()

    return mySC


foo = 42
bar = ["s", "p", "a", "m"]
baaz = {"parrot": "dead"}  

mySC = create_switch(foo, bar, baaz)
mySC(1)
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
0

you can simulate a switch statement using the following function definition:

def switch(v): yield lambda *c:v in c

Then, your code could look like this:

for case in switch(i):

    if case('1') : 
       return funcName1()

    if case('2'): 
       return funcName2()

    if case('3'): 
       return funcName3()
else:
    return 'Invalid'
Alain T.
  • 40,517
  • 4
  • 31
  • 51