'How to Define a Function in Python Which Its Name Contain a Variable? [closed]

Working with Python 2.7, How can i define a function which it's name has a variable? like:

for x in xrange(40):
  def functionname + x():
    print x

?



Solution 1:[1]

Store references to the functions in a list or dictionary.

To do this, let's make a function that makes the function which we will store in our list:

def functionmaker(x):
    def function():
        print(x)
    return function

This allows us to capture the value x at the time of the function's creation.

Now let's make a list of such functions:

functionlist = [functionmaker(x) for x in xrange(40)]

Now we can call them:

functionlist[5]()    # prints 5

Solution 2:[2]

This is insane.

Why not do:

def functionname(x):
    if x > 40:
        raise ValueError

And then handle each case however you please.

Solution 3:[3]

A slightly more Pythonic way than relying on exec(), is using the locals() dict.

from __future__ import print_function

for x in range(40):
    funcname = "functionname" + str(x)
    function = lambda x=x: print(x)
    locals()[funcname] = function

These lines were written by trained professionals. Don't try this at home... or do, it's just bad programming practice.

Two notes:

  • The print_function import makes it possible to print in lambdas
  • lambda x=x: is a workaround for one of Python's gotchas.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kindall
Solution 2 OJFord
Solution 3 NamaeNankaIranai