Python for a PHP user, how do i...?
Magnus Lie Hetland
mlh at idi.ntnu.no
Sat May 19 14:20:31 EDT 2001
"rw2" <richw at objenv.com> wrote in message
news:20010515.162432.2118421993.2310 at mayne.dhcp.fnal.gov...
> In article <9ds48t$1rt$1 at tyfon.itea.ntnu.no>, "Magnus Lie Hetland"
> <mlh at idi.ntnu.no> wrote:
>
> >> >>> spam="print 'eggs'"
> >> >>> eval(compile(spam,'<string>','exec'))
> >> eggs
> >>
> >> rw2
> >
> > Why the compile? Why not just eval(spam)?
>
> Try it.
Right. In this case you have a statement (print 'eggs') which
works with exec, but the question was about an expression, which
will work fine with eval().
> Now I'm not claiming there isn't a better way, just that the above method
> will work for any correct python not just single method invocations as
> eval seems to.
Use exec.
> I'm way out of my depth here as I have only had to stoop
> to such nonesense on one occasion and am therefore pretty unfamilar with
> the inner workings of eval and friends.
>
> Stop the presses. I just found 'exec'.
Right.
> That's the general purpose
> function I was looking for. Don't do the compile nonesense I previously
> recommended. exec does it for you in one cleaner step.
The only disadvantage is that it doesn't return anything... So you
can't do, for instance:
x = exec name + "()"
while you *can* do
x = eval(name + "()")
(You could always bind something in a namespace dictionary with exec,
but...)
There are of course numerous possibilities. You could get the function
object and call it:
f = eval(func_name)
y = f(x)
This is perhaps what fits best with the original question:
In PHP:
> $varName = "PrintDate";
> $varName(); // calls function "PrintDate"
In Python:
var = eval("PrintDate")
var() # calls function PrintDate
The shorter eval(varName)() is of course also legal, as an
alternative to $varName(). Not too much syntactic overhead
there...
> rw2
--
Magnus Lie Hetland http://www.hetland.org
"Reality is that which, when you stop believing in
it, doesn't go away." -- Philip K. Dick
More information about the Python-list
mailing list