indirect function calls and variable variables

Erik Max Francis max at alcyone.com
Wed May 21 00:55:50 EDT 2003


Randall Smith wrote:

> Question:  Is it feasible to make indirect function calls in python?
	...
> #what i'm trying to avoid
> def do_f(f):
>         if f == 'f1': f1()
>         if f == 'f2': f2()
>         if f == 'f3': f3()
>         if f == 'fInfinity': youGetThePoint()
> 
> #what i'd like to do instead
> def do_f(f):
>         f() # this doesn't work, but maybe you get the point.

Sure, try:

	dispatcher = {'f1': f1, 'f2': f2, 'f3': f3, ...}
	def do_f(f):
	    dispatcher[f]()

> While I'm at it, can Python do variable variables?
> In PHP:
>         $var = 'hey'
>         $$var = 'dude'
> 
>         echo $dude
> 
>         output: hey
> 
> I used this alot in PHP.  Is there a way to do it in Python?

You can do it using exec, but the best solution is a separate
dictionary.

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ I'm the woman whose / Three wishes came true
\__/  Lamya




More information about the Python-list mailing list