Quick question: forcing exec() within a specific namespace

Michael P. Reilly arcege at shore.net
Thu May 20 12:01:07 EDT 1999


Sarino Suon <pioneer at wam.umd.edu> wrote:
: In the interactive interpreter, when I call exec(), whatever objects are
: created belong to the __main__ module. What if I need the objects to be
: attached to a specific object, such as a class instance? Can this be done?

Surely it can.  You can pass dictionaries for the global and local
namespaces.

  >>> private = {}  # will get the builtins later
  >>> exec('a = 10', private, private)
  >>> private.keys()
  ['a', '__builtins__']
  >>> private['a']
  10
  >>>

The global and local arguments do not have to be the same and can be
any mapping object (UserDict, module, class, etc.)

You might want to look at the RExec class to see how exec is used there.

  -Arcege





More information about the Python-list mailing list