special case loading modules with imp

Steven Taschuk staschuk at telusplanet.net
Wed Jul 30 21:05:02 CEST 2003

Quoth Erendil at aol.com:
> Thanks! There's just one part I don't get... (I like to fully understand it 
> before I use it)
>      >>>exec sourcecode in mod.__dict__
> What exactly does that do?

It executes the source code in the given string, using the
module's dict as the namespace.


All assignment operations bind a name to an object.  This includes
simple assignment statements such as
    x = 3
but also statements such as
    def foo():
        # ...
(which binds the name 'foo' to a certain function object).  The
mapping from name to object is maintained using a dict, one dict
for each namespace of relevance.  The globals of a given module,
in particular, are stored in a dict known as moduleobj.__dict__.

(The local namespace of a function -- the namespace in which its
local variables are bound -- actually has a different
implementation, I think, for performance.  But ignore that.)

'exec ... in ...' specifies which dict to use as the namespace for
the executed code.  Example:

    >>> d = {}
    >>> exec 't = 3' in d
    >>> d['t']
    >>> exec 'def foo(x): return 11*x' in d
    >>> d['foo']
    <function foo at 0x401f2304>

Of course, name lookup uses the given namespace as well:

    >>> exec 'print foo(t)' in d

Thus my suggested "import by hand" code does what importing a
module usually does -- it executes the code in the module, thereby
usually populating the module dict with functions, classes, etc..

For more, see the Language Reference section on the exec
statement, and maybe the section on Python's data model too.

Steven Taschuk                                                 o- @
staschuk at telusplanet.net                                      7O   )
                                                               "  (

More information about the Python-list mailing list