dynamic construction of variables / function names

Duncan Booth duncan.booth at invalid.invalid
Thu Mar 30 02:16:59 EST 2006


Sakcee wrote:

> python provides a great way of dynamically creating fuctions calls and
> class names from string
> 
> a function/class name can be stored as string and called/initilzed
> 
> e.g
> 
> def foo(a,b):
>     return a+b
> 
> def blah(c,d):
>     return c*d
> 
> 
> list = ["foo", "blah"]
> 
> for func in list:
>      print func(2,4)
> 
> or similar items

No, that doesn't work. To convert a string to a function name you have to 
look it up in a suitable namespace, or store a list of functions instead of 
a list of strings. So something like this would work:

 lst = [foo, blah]
 
 for func in lst:
      print func(2,4)


> 
> 
> what is the way if the names of functions are some modification e.g
> 
> def Newfoo(a,b):
>     return a+b
> 
> def Newblah(c,d):
>     return c*d
> 
> list = ["foo", "blah"]
> 
> for func in list:
>      print "New"+func(2,4)
> 
> or define a variable
> 
> "New"+list[0] = "First Funciton"
> 
> 
> I think ,       print "New"+func(2,4)  and "New"+list[0] = "First
> Funciton"
> 
> will not work,  either eval or exec should be used
> is it correct way, is there a simple way, is this techniqe has a name?
> 
One common way is to group the functions you want callable together in a 
class and then use getattr to access them.

class Commands:
  def Newfoo(self, a,b):
      return a+b
 
  def Newblah(self, c,d):
      return c*d

  def call(self, fname, *args. **kw):
      fn = getattr(self, "New"+fname)
      return fn(*args, **kw)

cmds = Commands()
lst = ["foo", "blah"]
for func in lst:
    print cmds.call(func, 2, 4)



More information about the Python-list mailing list