[Tutor] Passing a variable to 'import'

Gregor Lingl glingl@aon.at
Thu, 20 Dec 2001 13:03:35 +0100


alan.gauld@bt.com schrieb:

> > > >>moduleName="someModule"
> > >
> > > >>def import_module(someModule):
> > >         import someModule
> >
> > Sounds like a job for my once-beloved "exec" statement. :)
>
> Rob, this time I agree with you :-)
>
> I think there may be other ways to do this using some of
> the internals of Python but in this case exec does seem
> the best option.
>

I think, this is not the case, because of the same reason, why
the following doesn't work properly ().

>>> def pival():
      import math
      return math.pi

>>> pival()
3.1415926535897931
>>> math.pi
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in ?
    math.pi
NameError: name 'math' is not defined
>>>

(Apparently the module math is only
imported locally (to the function-body))

Similarly we have:

>>> def import_module(someModule):
      """Imports a module (someModule as string)"""
      exec 'import ' + someModule


>>> import_module('math')
>>> math.pi
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in ?
    math.pi
NameError: name 'math' is not defined

I assume that the definer of the import_module()
function wants the module to be imported to the
'namespace' (?) from which the function is
called.
Otherwise such a function would not make much
sense. (Or am I wrong?)

Gregor