[Tutor] Still pondering dynamically named functions ...

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 20 Jul 2002 17:47:54 -0700 (PDT)


On Sat, 20 Jul 2002, Graeme Andrew wrote:

> Sorry but I am really struggling to understand if the follwoing is
> possible ..  I asked before but perhaps I did not ask it very clearly
> (and I am new to python) !!

Don't worry about it; let's take a look at your question.



> My problem is understanding how in Python I can call dynamically at
> runtime the name of a function I have just read from the configuration
> file ... ie assign a function name to a variable and then call the
> function using this variable.

One way to do this is with the getattr() function.  We can imagine that a
module is a container of variable names.  Here's an example:

###
>>> import string
>>> string.upper
<function upper at 0x8113314>
>>> getattr(string, 'upper')
<function upper at 0x8113314>
###



> I know I can use the 'exec function' but this does not allow me to
> access return values or dynamically create a class.
>
> The code would kinda looks like this  ...
>
>  # assign a function to variable name ...
>  myfunction == "function_a"

What we can do is something like:

    myfunction = globals()['function_a']

This is related to the getattr() technique above.  globals() gives us a
dictionary of all the attributes in the current module, and we can use it
to grab at that 'function_a'.


Let's try a small example in the interactive interpreter, just to make
this concrete:

###
>>> def a():
...     print "hey"
...
>>> def b():
...     print "how"
...
>>> def c():
...     print "who"
...
>>> def test():
...     name = raw_input("which function? ")
...     function = globals()[name]
...     function()
...
>>> test()
which function? a
hey
>>> test()
which function? b
how
###



But to tell the truth, I do feel a little awkward, because it feels like
there's a small inconsistancy here between the getattr() and globals()
approaches.  Does anyone know if there is a unified way of getting at
one's own module object, without using the 'globals()' function?


Please feel free to ask more questions about this.  Hope this helps!