Re: Building a function call?
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Building a function call?

From: Duncan Booth <duncan.booth@invalid.invalid>
Date: Wed Jul 13 2005 - 14:56:26 CEST

Francois De Serres wrote:
> Having a string: "dothat"
> and a tuple: (x, y)
> 1. What's the best way to build a function call like: dothat(x,y)?
>
> Assuming dothat is def'd in the same module,
> 2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200)))
> the right way to have it executed?
>
> If dothat is def'd in another module:
> 3. what would be the right way to initialize the globals to pass to
> eval ?
>
No, none of this is a good place to use eval.

aString = "dothat"
atuple = (x, y)

If aString is the name of a function in the current module:

   globals()[aString](*aTuple)

If aString is a function in another module:

   import otherModule
   vars(otherModule)[aString](*aTuple)

and if you don't know the name of the module in advance:

   otherModule = __import__(nameOfOtherModule)
   vars(otherModule)[aString](*aTuple)

Better still, collect all the functions you expect to be callable in this
way together in a dictionary and then you can be sure that you only call
something you intended to be callable.
Received on Thu Sep 29 16:55:34 2005