I give up... was: A = X > Y ? X : Y

Fredrik Lundh effbot at telia.com
Wed Feb 16 16:40:16 EST 2000


Michal Wallace <sabren at manifestation.com> wrote:
> Fredrik Lundh wrote in message ...
> >the problem here is that you'll evaluate the
> >expression in the function's own namespace,
> >not the callers.
> >
> >(you can use trickery or guile to get around
> >that, but I won't post that solution...)
>
> Okay, I give up... How do you:
>
> a) know what the caller's namespace even IS
> b) evaluate something in that namespace?

look carefully:

import sys

def magic_eval(s):
    try:
        raise None
    except:
        frame = sys.exc_traceback.tb_frame.f_back
        return eval(s, frame.f_globals, frame.f_locals)

> Wouldn't that be useful in general for
> experimenting with language enhancements,
> even if the code were a little hairy?

sure.  if you know what you're doing ;-)

def run_me():
    a = "it "
    b = "works!"
    print magic_eval("a+b")

</F>





More information about the Python-list mailing list