indirect function calls and variable variables

Cameron Laird claird at lairds.com
Wed May 21 08:41:43 EDT 2003


In article <3ECB06D6.DC23C280 at alcyone.com>,
Erik Max Francis  <max at alcyone.com> wrote:
>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.
			.
			.
			.
I'll provide more detail.

PHPers do indeed use variable variables often--too much,
in fact.  It's a general principle that languages which
facilitate variable variables also are likely to offer
a dictionary or associative array, and most uses of
variable variables would better be recoded in terms of
dictionaries.  There are PHP folk who know this already.
If there's a question about it, someone invite me to 
compl.lang.php, and I'll elaborate.

Erik illustrated the pattern with his function invocation
above.  He didn't write there that such usage generally
invites consideration for refactoring into an object-
oriented polymorphism scheme.  I leave that as an exercise
for the reader.  He also didn't observe that, yes, do_f is
feasible in a more narrow sense, using either of at least
a couple of distinct approaches.  Here's an illustration:
  
  def do_f(f):
	  # You can do much the same with exec, instead.
      eval("%s()" % f)
  
  def do_f_other(f):
	  # Other evaluations involve call() or __getattr__().
      (globals()[f])()
  
  def f1():
      print "I am f1."
  
  def f2():
      print "I am f2."
  
  do_f("f1")
  do_f("f2")
  do_f_other("f1")

Finally, can Python process variable variables?  Sure, but,
again, I'll warn you against this; there are usually better
ways:
  var = 'hey'
  dude = 'var'
  print eval(dude)

Also, your original PHP example doesn't do what you say it
does.  I leave this, too, as an exercise for the reader.
-- 

Cameron Laird <Cameron at Lairds.com>
Business:  http://www.Phaseit.net
Personal:  http://phaseit.net/claird/home.html




More information about the Python-list mailing list