indirect function calls and variable variables

Peter Abel p-abel at t-online.de
Wed May 21 08:39:12 EDT 2003


Randall Smith <randall at tnr.cc> wrote in message news:<LmDya.10043$ui.368085 at twister.austin.rr.com>...
> Question:  Is it feasible to make indirect function calls in python?
> 
> Example:
> 
> 
> def f1():
> 	blah blah
> 	blah blah
> def f2():
> 	foo doo
> 	doo foo
> def f3():
> 	yik yak
> 	mee yow
> def fInfinity():
> 	yo yo
> 	yaw yaw
> 
> #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.
> 
>
It depends, how you want to use **do_f(f)**. Either f is
a functionpointer or a string.
1) Functionpointer (as easy, as you want):
>>> def f1():
... 	print 'f1()'
... 	
>>> def f2():
... 	print 'f2()'
... 	
>>> def f3():
... 	print 'f3()'
... 	
>>> def do_f(f):
... 	f()
... 	
>>> do_f(f1)
f1()
>>> do_f(f2)
f2()
>>> do_f(f3)
f3()
2) As string (nearly as easy):
>>> def do_f_asText(f):
... 	eval(f)()
... 	
>>> do_f_asText('f1')
f1()
.
and so on
.
> 
> 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?
> 
Sure
>>> var='hey'
>>> dude='var'
>>> eval(dude)
'hey'
>>> var='Something else'
>>> eval(dude)
'Something else'
>>> 
> Randall

Regards, Peter




More information about the Python-list mailing list