1

I was trying to code something with the use of a python switch, simulated in a dict as suggested in: Replacements for switch statement in Python? [Second answer, by Nick]

When I tested, for some reason all the functions inside were being called, tried a simple code to see what was wrong and the problem repeated. See:

def switch(f):
    print('Switch got: ', f)
    var = {
        1: func1(),
        2: func2(),
        3: func3()
        }.get(f,False)
    return var

def func3():
    fb = 'Func3 called'
    print(fb)
    return fb

def func1():
    rsp = 'Func1 called'
    print(rsp)
    return rsp

def func2():
    rsp = 'Func2 called'
    print(rsp)
    return rsp

var = switch(1)
print(var)

My expected return was just:

Switch got:  1
Func1 called

Instead i got:

Switch got:  1
Func1 called
Func2 called
Func3 called
Func1 called

What I got from it is that python seems to run every func inside the dict before calling the proper key (1 in the example).

Is this the expected behavior in Python?

Is there a way around, where only the function that corresponds to the key is called?

Justcurious
  • 1,952
  • 4
  • 11
  • 17

2 Answers2

6

Is this the expected behavior in Python?

Yes.

Is there a way around, where only the function that corresponds to the key is called?

Don't actually call the functions when you create your dispatch dict:

def switch(k):
    print('Switch got: ', k)
    func = {
        1: func1,
        2: func2,
        3: func3,
    }.get(k, bool)
    var = func()
    return var
wim
  • 338,267
  • 99
  • 616
  • 750
1

The act of initializing that dictionary when the function 'switch' is called also calls the functions. Try something like this,

def switch(f):
    print('Switch got: ', f)
    var = {
        1: func1,
        2: func2,
        3: func3
        }.get(f,False)
    if not var:
      return false
    return var()
JonAmazon
  • 92
  • 4