-1

Im trying to implement a menu in my tool. But i couldn't implement a switch case in python. i know that python has only dictionary mapping. How to call parameterised methods in those switch case? For example, I have this program

def Choice(i): switcher = { 1: subdomain(host), 2: reverseLookup(host), 3: lambda: 'two' } func = switcher.get(i, lambda:'Invalid') print(func())

Here, I couldn't perform the parameterised call subdomain(host). Please help.

martineau
  • 119,623
  • 25
  • 170
  • 301
Adithyan AK
  • 1
  • 1
  • 1

4 Answers4

3

I think the problem is because the first two functions are getting called when the switcher dictionary is created. You can avoid that by making all of the values lambda function definitions as shown below:

def choice(i):
    switcher = {
            1: lambda: subdomain(host),
            2: lambda: reverseLookup(host),
            3: lambda: 'two'
        }
    func = switcher.get(i, lambda: 'Invalid')
    print(func())
martineau
  • 119,623
  • 25
  • 170
  • 301
0

Switch cases can be implemented using dictionary mapping in Python like so:

def Choice(i):
    switcher = {1: subdomain, 2: reverseLookup}
    func = switcher.get(i, 'Invalid')
    if func != 'Invalid':
        print(func(host))

There is a dictionary switcher which helps on mapping to the right function based on the input to the function Choice. There is default case to be implemented which is done using switcher.get(i, 'Invalid'), so if this returns 'Invalid', you can give an error message to user or neglect it.

The call goes like this:

Choice(2)  # For example

Remember to set value of host prior to calling Choice.

Austin
  • 25,759
  • 4
  • 25
  • 48
0

There is an option that is obvious to get correct..:

def choice(i, host):  # you should normally pass all variables used in the function
    if i == 1:
        print(subdomain(host))
    elif i == 2:
        print(reverseLookup(host))
    elif i == 3:
        print('two')
    else:
        print('Invalid')

if you're using a dictionary it is important that all rhs (right-hand-sides) have the same type, i.e. a function taking zero arguments. I prefer to put the dict where it's used when I use a dict to emulate a switch statement:

def choice(i, host):
    print({
        1: lambda: subdomain(host),
        2: lambda: reverseLookup(host),
        3: lambda: 'two',
    }.get(i, lambda: 'Invalid')())   # note the () at the end, which calls the zero-argument function returned from .get(..)
thebjorn
  • 26,297
  • 11
  • 96
  • 138
-1

try this ....

def Choice(i):
    switcher = {
            1: subdomain(host),
            2: reverseLookup(host),
            3: lambda: 'two'
        }
    func = switcher.get(i, lambda:'Invalid')
    print(func())



if __name__ == "__main__": 
    argument=0
    print Choice(argument)