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
else:
import all_the_other_modules
Now how can I have the imported modules globally available?
For example:
conditional_import_modules(test='bar')
thirdmodule.myfunction()
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.Example:
You can use the built-in function
__import__
to conditionally import a module with global scope.To import a top level module (think:
import foo
):Import from a hierarchy (think:
import foo.bar
):Import from a hierarchy and alias (think:
import foo.bar as bar
):I like @rafał grabie approach. As it even support importing all. i.e. from os import *
(Despite it being bad practice XD )
Not allowed to comment, but here is a python 2.7 version.
Also removed the need to call the function at the end.
You can make the imports global within a function like this:
You could have this function return the names of the modules you want to import, and then use
I like @badzil approach.
So something that is traditionally in a class module:
Can be transformed into a global scope:
May have some bugs, which I will verify and update. The last example could also have an alias which would be another "shortname" or a hack like "importr|aliasimportr"