Can Python do this?

Ype Kingma ykingma at accessforall.nl
Mon Mar 4 14:27:19 EST 2002


Robert Oschler wrote:
> 
> Hello, Python newbie here.
> 
> Let's say I'd like to build a method name into a string variable (e.g.
> "FuncCall" + "1" to attempt to call "FuncCall1").  Can I then call that
> method by somehow having the interpreter evaluate the string variable into a
> call to the desired method? (I know this is usually done in a language like
> Prolog or Lisp but I'm hoping Python can do it too.)

Although you'd probably better use a dictionary of functions,
you might try:

  result = eval("FuncCall" + "1" + "()")

or:
 
  function = globals()["FuncCall" + "1"]
  result = function()

or:

  import sys
  function = getattr(sys.modules[__name__], "FuncCall" + "1")
  result = function()

In case you need a variable number of arguments, have a look
at apply:

  theArgs = (1,2,3)
  result = apply(function, theArgs)


Have fun. Python can be quite Lispy.

Ype



More information about the Python-list mailing list