tags:

views:

119

answers:

6

Hello,

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.

Thanks!

+4  A: 

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
...
Manoj Govindan
Yeah, I wanted to define them statically in the source file. I can script them, though so many functions wastes space. Thanks for the explanation on how to do it at runtime.
Jasie
A: 

There's already a thread that talks about dynamic code generation in detail. Refer: http://stackoverflow.com/questions/533382/dynamic-runtime-method-creation-code-generation-in-python

Goutham
-1 if you're going to go rep whoring by posting what should be a comment as an answer then at least make sure that the link is valid. That link is all about dynamically added _methods_. OP is asking about _functions_.
aaronasterling
@aaronasterling thanks for letting me know that it should have been a comment. But my link is still valid. If you read the answer in the linked thread, there is only a slight modification required. Figure that one as an exercise. BTW, you are unnecessarily rude.
Goutham
A: 

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.

Andrey Vlasovskikh
+1  A: 

Maybe you could adapt this recipe for your needs.

from functools import partial
class FunctionPool:
    def __init__(self,function):
        self.function = function
    def __getitem__(self,item):
        return partial(self.function,item)

>>> @FunctionPool
def func(item,param):
    print "function#{item} called with {param}".format(
        item = item,
        param = param )
>>> f = func[2]
>>> f(3)
function#2 called with 3
Odomontois
very nice. fun fact: spaces don't count towards minimum comment length
aaronasterling
A: 

How about:

from __future__ import print_function

activate_field_ = [lambda i=i: print(i) for i in range(11)]

for x in range(1, 11):
    activate_field_[x]()

This creates one extra function, activate_field_[0] which prints '0', but you can just not use it.

martineau
+1  A: 

Here's another two line answer that produces function names exactly like you wanted (and is a bit simpler than the "Dynamic/runtime method creation" answer pointed out by @Goutham):

fntemplate = """def activate_field_%d(): print %d"""
for x in range(1, 11): exec fntemplate % (x,x)

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