Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic switch within class

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.

like image 681
heiiRa Avatar asked Mar 07 '23 18:03

heiiRa


1 Answers

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(...)()
like image 114
deceze Avatar answered Mar 20 '23 09:03

deceze