Indentation and grouping proposal

Michael P. Reilly arcege at
Tue Jun 8 11:57:22 EDT 1999

Emile van Sebille <emile at> wrote:
: Re: One Liners:

:>>> def myexec(b):
: ...  for stmnt in string.split(b,'\n'):
: ...   exec(stmnt)
: ...
:>>> b="if a: print 'Spam!';print 'Spam2!';\nprint'Yum!'"
:>>> myexec(b)
: Yum!
:>>> a=1
:>>> myexec(b)
: Spam!
: Spam2!
: Yum!

Unfortunately, this doesn't work in other namespaces and frames,  but
the following does.

$ cat
def myexec(stmts):
  import string, sys
    raise SystemError
  except SystemError:
    tb = sys.exc_info()[-1]
  f = tb.tb_frame.f_back
  g, l = f.f_globals, f.f_locals
  del tb, f
  for stmt in string.splitfields(stmts, '\n'):
    exec stmt in g, l

$ cat
import fexec

def foo(x):
  fexec.myexec('print x')

$ python

The trick is to get locals and globals of myexec's caller (which could
be in another module).  But, do we know how safe this is? ;)


More information about the Python-list mailing list