how to distinguish a python expression from a statement?

James_Althoff at i2.com James_Althoff at i2.com
Wed Sep 5 13:26:38 EDT 2001


Thanks, Fredrik.  That's perfect!

Jim

Fredrik Lundh wrote:
==========================

James_Althoff at i2.com wrote:
> I must be doing something wrong, though, because I don't seem to be
getting
> the expected behaviour.  The magic "_" variable works when I type
directly
> into the Python interpreter (interactive mode).  But when I run your
> example code using either Python or Jython, "_" is not defined (as part
of
> the exec statement).

oh, sorry -- my test program was flawed, and my brain is
still on vacation.

Let's try again:

When you execute a "single" code object, the result is stored
in the variable "_", which lives in the "built-in" namespace.  If
the code object doesn't generate a result, the variable is not
changed.

You can reach this variable through dict's "__builtins__" member
(after you've executed the code), or by importing the __builtin__
module.

Some variation of this could work:

import __builtin__

def test(code):
    if hasattr(__builtin__, "_"):
        del __builtin__._
    dict = {} # use a clean namespace
    exec compile(code, "<string>", "single") in dict
    if hasattr(__builtin__, "_"):
        print "expression:", __builtin__._
    else:
        print "statement"

test("1+1")
test("print 1+1")

</F>


--
http://mail.python.org/mailman/listinfo/python-list






More information about the Python-list mailing list