how to distinguish a python expression from a statement?

James_Althoff at James_Althoff at
Wed Sep 5 19:26:38 CEST 2001

Thanks, Fredrik.  That's perfect!


Fredrik Lundh wrote:

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

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

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__._
        print "statement"

test("print 1+1")



More information about the Python-list mailing list