4

I am trying to build a switch logic in python.

Based on Replacements for switch statement in Python? I build the following code:

def func(string):
    print(string)

class Switch:
    def __init__(self):
        pass

    def first_switch(self, case):
        return {
             '1': func('I am case 1'),
             '2': func('I am case 2'),
             '3': func('I am case 3'),
             }.get(case, func('default'))


switch = Switch()
switch.first_switch('2')

This will give me the output:

I am case 1
I am case 2
I am case 3
default

I expected the output to be

I am case 2

Is this dictionary-case-logic only applicable outside of a class definition or did I miss some additional code? Looks like all dictionary key-value pairs are evaluated at the function call.

heiiRa
  • 113
  • 7
  • The value is the *result* of calling the function. Why not just store the strings, then call `func` on whatever you get out of the dictionary? Also, why bother with `func` when it's just `print`? – jonrsharpe Oct 24 '17 at 10:49
  • If you want to store values, func should return its argument. Right now your dictionary is all Nones. – JL Peyret Oct 24 '17 at 18:28

1 Answers1

7

You're always calling all those functions while building the dictionary. It has nothing to do with classes.

d = {'foo': bar()}

bar is being called here and its return value assigned to d['foo']. Remember, this isn't a switch statement; it's a dictionary literal that's used to sort of emulate a switch statement.

In your case, the function isn't variable, so doesn't have to be included at all:

arg = {
    '1': 'I am case 1',
    '2': 'I am case 2',
    '3': 'I am case 3',
}.get(case, 'default')
func(arg)

If the function is variable as well, you want to make the dictionary values callables which will call the function when called:

{'1': lambda: func('I am case 1'), ...}.get(...)()
                    # call the function you got ^^

Or perhaps:

from functools import partial

{'1': partial(func, 'I am case 1'), ...}.get(...)()
deceze
  • 510,633
  • 85
  • 743
  • 889
  • Sorry for the inappropriate example, the function I want to call is indeed variable and thus your `lambda` expression is the key! Thanks for your explanation! – heiiRa Oct 25 '17 at 08:10