Giovanni Di Milia Giovanni Di Milia - 1 year ago 79
Python Question

Python: how to make global imports from a function

I fear that this is a messy way to approach the problem but...

let's say that I want to make some imports in Python based on some conditions.

For this reason I want to write a function:

def conditional_import_modules(test):
if test == 'foo':
import onemodule, anothermodule
elif test == 'bar':
import thirdmodule, and_another_module
import all_the_other_modules

Now how can I have the imported modules globally available?

For example:


Answer Source

Imported modules are just variables - names bound to some values. So all you need is to import them and make them global with global keyword.


>>> math
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
>>> def f():
...     global math
...     import math
>>> f()
>>> math
<module 'math' from '/usr/local/lib/python2.6/lib-dynload/'>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download