Troels Folke
Troels Folke

Reputation: 927

Can one define functions like in JavaScript?

In Python, can one define a function (that can have statements in it, thus not a lambda) in a way similar to the following JavaScript example?

var func = function(param1, param2) {
    return param1*param2;
};

I ask, since I'd like to have a dictionary of functions, and I wouldn't want to first define all the functions, and then put them in a dictionary.

The reason I want a dictionary of functions is because I will have another function that takes another dictionary as parameter, loops through its keys, and if it finds a matching key in the first dictionary, calls the associated function with the value of the second dictionary as parameter. Like this:

def process_dict(d):
     for k, v in d.items():
         if k in function_dict:
             function_dict[k](v)

Maybe there is a more pythonic way to accomplish such a thing?

Upvotes: 2

Views: 122

Answers (1)

kindall
kindall

Reputation: 184280

Use a class (with static methods) instead of a dictionary to contain your functions.

class MyFuncs:

    @staticmethod
    def func(a, b):
        return a * b

    # ... define other functions

In Python 3, you don't actually need the @staticmethod since class methods are simple functions anyway.

Now to iterate:

def process_dict(d):
   for k, v in d.items():
       getattr(MyFuncs, k, lambda *x: None)(*v)

N.B. You could also use a module for your functions and use import.

Upvotes: 2

Related Questions