views:

56

answers:

4

I would like to know why

 >>> def func2():
...     global time
...     import time
...
>>> time
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'time' is not defined
>>> func2()
>>> time
<module 'time' (built-in)>
>>>

works, but

   >>> def func():
...     global module
...     module="time"
...     exec ("global %s" %module)
...     exec ("import %s" %module)
...
>>> time
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'time' is not defined
>>> func()
>>> time
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'time' is not defined

works not, and how i could get it to work =) thank you

+7  A: 

Each of your exec() calls happens in a separate namespace. Abandon this path; it will only lead to ruin.

Ignacio Vazquez-Abrams
ok thank you =) exec ("global %s;import %s" %(module,module)) works
Skince
+1  A: 

Because exec uses its own scope by default. If you do exec "global {0}; import {0}".format(module) in globals(), then it'll work.

You shouldn't be doing that, unless you really need to.

PiotrLegnica
I don't think anybody really *needs* to use exec like this.
Lukáš Lalinský
*Nobody* needs exec, this is Python after all.
THC4k
A: 

What you are trying to do is either very sophisticated or very odd. This is how it works:

exec ("import %s" % module) in globals()

Please describe the bigger problem you are trying to solve

Otto Allmendinger
I'm trying to import a module which the user specifies. Is there another way?
Skince
@Skince, yes there is a better way, see my answer
gnibbler
+1  A: 

To import a module given the name as a string use

time=__import__('time')

Here's one way you might use it

usermodulenames = ["foo","bar","baz"]
usermodules = dict((k,__import__(k)) for k in usermodulenames)
gnibbler
How would i call the functions from time , when its not sure it is "time"? It would be a user input.
Skince
@Skince, you can call it whatever you like. Let me add to my answer
gnibbler