[Tutor] Dynamically naming functions

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Mar 10 20:17:14 CET 2006


> I want to use this in a few different places.  For example Faces, the
> Python Project Management Planner Tool Thingy, uses nested functions to
> put tasks within a project:
>
> def MyProject():
>     start = "2006-03-06"
>     resource = Me
>
>     def Task1():
>         start = "2006-03-13"
>
>     def Task2():
>         effort = "1w"
>
> I'd like to load these from a database (using SQLObject), but I'm not
> sure how I can define the name of the function from a filed in a
> database (or read in from a text file).

Hi Ed,

If we have a bunch of functions in a module, then we can get at a function
from its string name by using the getattr() built-in function.

    http://www.python.org/doc/lib/built-in-funcs.html#l2h-31


For example, let's say that we have a module like the math module.

######
>>> import math
######

We know that we can get the function by naming it.

######
>>> math.sin
<built-in function sin>
>>> math.sin(3.14)
0.0015926529164868282
######


But we can also get it if we have a string:

######
>>> def getMathFunction(name):
...     return getattr(math, name)
...
>>> getMathFunction("sin")
<built-in function sin>
>>> getMathFunction("sin")(3.14)
0.0015926529164868282
######

And of course, that string can come from anywhere, including a database.



Does this answer your question?  If you have questions, please feel free
to ask.



More information about the Tutor mailing list