Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Functions in Dictionary [Python]

I'm currently building an application where I need to iterate over a series of steps that do largely the same thing, save a very small amount of code (~15 lines). The number of steps will vary depending on how the project is configured, so it seems kind of silly for me to create a separate function for each potential instance.

In JavaScript, I would do something like this:

var switches = [true, true, false, true];

var holder = {
    0: function() { /* do step0 */ }
    1: function() { /* do step1 */ }
    2: function() { /* do step2 */ }
    3: function() { /* do step3 */ }
    // ...etc...
}

for (var i = 0; i < switches.length; i++)
    if (switches[i])
        holder[i]();

Is there a way to do something similar to this in python? The only thing I can think of is something like this:

switches = [True, True, False, True]

class Holder(object):
    @staticmethod
    def do_0():
        # do step0

    @staticmethod
    def do_1():
        # do step 1

    # ...etc...

    def __repr__(self):
        return [self.do_0, self.do_1, ...]

for action in Holder:
    action()

This just seems terribly inefficient if I have any significant number of steps. Is there any better way to go about this?

like image 423
Robert Ingrum Avatar asked Mar 24 '15 23:03

Robert Ingrum


People also ask

Can you store functions in a dictionary Python?

Given a dictionary, assign its keys as function calls. Case 1 : Without Params. The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets '()' are added.

How do you store functions in Python?

October 12, 2021. In Python, you can save the definitions of functions in a file called a module. It is possible to import module definitions into your program file. We can save our Python functions in their own file, which is a module, then the module is imported to the main program.

What can you store in a dictionary Python?

Python's dictionary allows you to store key-value pairs, and then pass the dictionary a key to quickly retrieve its corresponding value. Specifically, you construct the dictionary by specifying one-way mappings from key-objects to value-objects. Each key must map to exactly one value, meaning that a key must be unique.

Can we define function in dictionary Python?

Python defines a function by executing a def statement. Python defines your dict by executing your d = { etc etc etc} .


2 Answers

You can do this as follows:

# define your functions
def fun1():
    print("fun1")

def fun2():
    print("fun2")

def fun3():
    print("fun3")


switches = [True, False, True];

# put them in a list (list makes more sense than dict based on your example)
func_list = [fun1, fun2, fun3]

# iterate over switches and corresponding functions, and execute 
# functions when s is True    
for s,f in zip(switches, func_list):
    if s: f() 

This is one way only. There are many others. e.g. using lambdas, dict as you wanted, etc.

To use lambdas if your functions are one line only, you can do:

func_list = [lambda: print("lambda1"), 
             lambda: print("lambda2"), 
             lambda: print("lambda1")]
like image 133
Marcin Avatar answered Sep 28 '22 07:09

Marcin


It looks like there isn't a way to do this in Python, a design decision made intentionally since it was dismissed as un-Pythonic. Oh well, it looks like I'm stuck defining the methods and then manually adding them to a list to iterate through.

Source: https://softwareengineering.stackexchange.com/a/99245

like image 36
Robert Ingrum Avatar answered Sep 28 '22 06:09

Robert Ingrum