Judismar Arpini Junior
Judismar Arpini Junior

Reputation: 431

How can I define function names with variable contents in Python?

Basically, what I want to do is this:

for i in range(10):
  def function[i_value]():
    pass

Which would define these functions: function0, function1, ..., function9.

Upvotes: 0

Views: 35

Answers (1)

DeepSpace
DeepSpace

Reputation: 81604

If these functions are going to be a single-line expressions-only functions you can use lambda:

for name in ['func_1', 'func_2']:
    name = lambda: None

Though I don't see why you would want to do it, as the functions won't be accessible once the for loop is done.

You can store them in a dict though for later access:

funcs = {}
for name in ['func_1', 'func_2']
    funcs[name] = lambda: None

print funcs['func_1'] 

>> <function <lambda> at 0x0019B1E0>

Upvotes: 1

Related Questions