Nina
Nina

Reputation: 5

Iterating through functions in Python

I would like to be able to do the following, in Python 2.7:

    for function in ['function1', 'function2', 'function3', 'function4']:
        some_dictionary [function] = function (an_argument)

However, when I try to do so, an error rises. The following code does the thing I would like the upper code to do:

    some_dictionary ['function1'] = function1 (an_argument)
    some_dictionary ['function2'] = function2 (an_argument)
    some_dictionary ['function3'] = function3 (an_argument)
    some_dictionary ['function4'] = function4 (an_argument)

Is there a more compact way of writing the latter code, something similar to the former one?

Thanks in advance,

Logicum

Upvotes: 0

Views: 213

Answers (3)

kindall
kindall

Reputation: 184455

for function in ['function1', 'function2', 'function3', 'function4']:
    some_dictionary[function] = function(an_argument)

This won't work because the items in the list are strings, and you can't call strings. Instead, put the actual functions in the list.

for function in [function1, function2, function3, function4]:
    some_dictionary[function.__name__] = function(an_argument)

You can also use the function itself as a key, which can be useful in some circumstances (for example, you can put a description of the function in its docstring and use that to print something nice for the user, or you can allow the user to retry the function, or whatever): It's much simpler to keep the function reference for later use, in other words, than to try to get it from the function name.

for function in [function1, function2, function3, function4]:
    some_dictionary[function] = function(an_argument)

Upvotes: 5

Nir Alfasi
Nir Alfasi

Reputation: 53565

If you have the names of the functions as strings, you can use locals() to access them:

def function1():
    print "in function1"

def function2():
    print 'in function2'

some_dictionary = {}

for func in ['function1', 'function2']:
    some_dictionary[func] = locals()[func]

print some_dictionary['function1']()

prints:

in function1

Upvotes: 0

Nafiul Islam
Nafiul Islam

Reputation: 82600

You can use func_name:

>>> a = lambda x: x + 1
>>> b = lambda y: y + 2
>>> c = lambda z: z + 3
>>> a.func_name = 'a'
>>> b.func_name = 'b'
>>> c.func_name = 'c'
>>> z = a, b, c
>>> d = {}
>>> for f in z:
...     d[f.func_name] = f(10)
...
...
>>> d
{'a': 11, 'c': 13, 'b': 12}

Using lambdas here, so everything is name <lambda>, but with proper functions, their func_names will reflect their variable names.

Upvotes: 0

Related Questions