views:

138

answers:

4

I've got a problem trying to get python to accept an import 'globally'

In a module it needs to import another module depending on another variable but it doesn't seem to import it into all of the module functions if i have it in the start function; for example:

def start():
    selected = "web"
    exec("from gui import " + selected + " as ui")
    log("going to start gui " + selected)
    ui.start()

this works but in the same module:

def close():
    ui.stop()

doesn't work. i don't know what's going on here

Joe

A: 

You can provide scope of exec with in. Try this:

exec("from gui import " + selected + " as ui") in globals()
Imran
A: 

You are importing the ui module to the start() function scope only. You should import the module to global scope. To do this you could import the module before the two functions (start and close) or provide global scope to exec() function.

Example: To provide global scope to the exec method.

exec("from gui import " + selected + " as ui") in globals()
Pedro Ghilardi
thnx. you got the same answer but i had to pick one of them
Joe Simpson
You made the right choice. The message written by Imram was sent before. =]
Pedro Ghilardi
+2  A: 

Why do you want to do it this way? Why not use the __import__ builtin? Also, your binding to gui is local to the function start.

Noufal Ibrahim
+4  A: 
import gui
ui = None

def start():
  selected = "web"
  log("going to start gui " + selected)
  global ui
  __import__("gui.%s" % selected) # if you're importing a submodule that
                                  # may not have been imported yet
  ui = getattr(gui, selected)
  ui.start()
Roger Pate
+1: There's always a simpler, cleaner way.
S.Lott
This doesn't work if "selected" is a submodule. For that, do a "__import__('ui.' + selected)" first.
Andrew Dalke