Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically define functions?

Tags:

python

I have functions like this:

def activate_field_1():
   print 1

def activate_field_2():
   print 2

def activate_field_3():
   print 3

How do I define activate_field_[x] for x=1:10, without typing out each one of them? I'd much rather pass a parameter, of course, but for my purposes this is not possible.

like image 211
atp Avatar asked Sep 10 '10 19:09

atp


People also ask

How do you create a dynamic function?

Creating The Dynamic Function The Function object can also be used as a constructor function to create a new function on the fly. The syntax for creating a function from Function Object is as follows: const myFunction = new Function(arg1, arg2, … argN, body);

How do you dynamically define a function in Python?

Method 1: exec() It's the perfect way to dynamically create a function in Python! ? Python's built-in exec() executes the Python code you pass as a string or executable object argument. This is called dynamic execution because, in contrast to normal static Python code, you can generate code and execute it at runtime.

What is a dynamic function?

Dynamic function is a way of dynamically invoking a function call. The compiler will have limited knowledge of what you are up to so you will get run time errors if you don't use correct inputs and outputs. One example that runs different functions depending on user input: DEFINE VARIABLE iFunc AS INTEGER NO-UNDO.

What is dynamic function in JavaScript?

The dynamic nature of JavaScript means that a function is able to not only call itself, but define itself, and even redefine itself. This is done by assigning an anonymous function to a variable that has the same name as the function.


3 Answers

Do you want to define these individually in your source file, statically? Then your best option would be to write a script to generate them.

If on the other hand you want these functions at runtime you can use a higher order function. For e.g.

>>> def make_func(value_to_print):
...     def _function():
...         print value_to_print
...     return _function
...
>>> f1 = make_func(1)
>>> f1()
1
>>> f2 = make_func(2)
>>> f2()
2

You can generate a list of these and store, again at runtime.

>>> my_functions = [make_func(i) for i in range(1, 11)]
>>> for each in my_functions:
...     each()
...
1
2
3
...
like image 116
Manoj Govindan Avatar answered Oct 17 '22 01:10

Manoj Govindan


Here's something that produces function names exactly like you wanted (and is a little simpler than the Dynamic/runtime method creation's accepted answer mentioned in @Goutham's now deleted answer):

FUNC_TEMPLATE = """def activate_field_{0}(): print({0})"""
for x in range(1, 11): exec(FUNC_TEMPLATE.format(x))

>>> activate_field_1()
1
>>> activate_field_7()
7

In Python versions 3.6+, it can be written as shown below using so-called f-string literals:

for x in range(1, 11): exec(f"""def activate_field_{x}(): print({x})""")
like image 29
martineau Avatar answered Oct 17 '22 03:10

martineau


You may put new symbols into the dictionary of current variable bindings returned by vars():

for i in range(1, 11):
    def f(x):
        def g():
            print x
        return g
    vars()['activate_field_%d' % i] = f(i)

>>> activate_field_3()
3

But this trick is generally not recommented unless you definitely sure you need it.

like image 5
Andrey Vlasovskikh Avatar answered Oct 17 '22 03:10

Andrey Vlasovskikh