import question

Calvelo Daniel dcalvelo at pharion.univ-lille2.fr
Fri Nov 3 06:49:01 EST 2000


kopfarzt at my-deja.com wrote:

: what I want to do is something like this:
:
: def a():
:   module = __import__ ('foo')
:
: def b():
:   x = eval ('foo.bar ()')
:
: I always get a NameError: foo
: (I am using Python 1.5.2)

This is because:

1) you have imported 'foo' under the name 'module'.

2) 'module' is only visible within the scope of 'a'.

Is the following that you are trying to do?

>>> def a():
...   global aa
...   aa = __import__('re')
... 
>>> def b():
...   print aa.__file__
... 
>>> a()
>>> b()
/usr/lib/python1.5/re.pyc

If yes, remember that you can:

>>> import pickle
>>> p = pickle
>>> p
<module 'pickle' from '/usr/lib/python1.5/pickle.pyc'>

And in Python2.0, you can also:

>>> import pickle as p
>>> pickle
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: There is no variable named 'pickle'
>>> p
<module 'pickle' from '/home/tmp/Python-2.0/Lib/pickle.py'>

Besides, you can always build a namespace "by hand" and then use the
globals and locals in the call to eval:

>>> print eval.__doc__
eval(source[, globals[, locals]]) -> value

Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals and locals are dictionaries, defaulting to the current
globals and locals.  If only globals is given, locals defaults to it.

It can get really convoluted:

>>> def a():
...   import pickle as p      
...   global e          
...   e = {'mypickle':p}
... 
>>> a()
>>> eval(' mypickle', e )
<module 'pickle' from '/home/tmp/Python-2.0/Lib/pickle.py'>

HTH, DCA

-- Daniel Calvelo Aros
     calvelo at lifl.fr



More information about the Python-list mailing list