3

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.

2
  • 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? Commented Oct 24, 2017 at 10:49
  • If you want to store values, func should return its argument. Right now your dictionary is all Nones. Commented Oct 24, 2017 at 18:28

1 Answer 1

6

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(...)()
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.