Import at file level inside a function? (Python 2)
Question: Is it possible to do something like this?

    
    
    def loadModules():
      import time
      from myModule import *
    
    def runFunction():
      try:
        print str(time.time())
        print myFunction() # myFunction is in myModule (myModule.myFunction)
      except NameError:
        raise RuntimeError("Module was not initialized. Call loadModules() first.")
    
    if (__name__ == "__main__"):
      # this should fail
      try:
        runFunction()
      except RuntimeError:
        print "Exception raised as expected."
    
      loadModules()
    
      runFunction() # it should work now
    

This will not work as expected because importing the modules _inside_ the
loadModules function will not declare them at a file level.

For modules like `time` I could add a `global time` statement after the
import. However, how can I accomplish this for a situation where the items
imported are unknown, as in `from myModule import *`? I won't automatically
know the name of every function in `myModule`. And even if I did, that'd be an
ugly global statement.

Essentially, can I basically take all local variables and make them global?

EDIT: This seemed to work in test code:

    
    
    def test():
        import time
        global time
        print "Inside test function: %s" % str(time.time())
    
    test()
    print "outside function: %s" % str(time.time())
    

This also worked:

    
    
    def test():
        from time import time
        global time
        print "Inside test function: %s" % str(time())
    
    test()
    print "outside function: %s" % str(time())
    

This however did not work:

    
    
    def test():
        import time
        print "Inside test function: %s" % str(time.time())
    
    test()
    print "outside function: %s" % str(time.time())
    


Answer: This is a horrible idea, even if it could ever work, which it couldn't.

Putting a `global` statement after the import will have exactly zero effect.
The only thing that does is mark that name as global _within the current
scope_. Once the function returns, the caller will still have no knowledge of
the imported names.

In any case, you shouldn't ever be using `from MyModule import *` anyway.

