Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importlib.import_module adding * to globals? [duplicate]

Tags:

python

Trying to dynamically add settings attributes to globals() according to some dynamic environment variables.

import os
from importlib import import_module


# To support environment variables as the means of specifying
# the target environment as an alternative to using the --settings flag
# where MY_ENV is 'local', 'development', 'staging', 'production'
if os.environ.get('MY_ENV'):
    env = os.environ.get('MY_ENV')
    import_module('my.settings.%s' % env, '*')

Its understood that import_module needs to be assigned to a variable:

foo = import_module('path.to.package', 'bar')

and that:

globals()[foo] = foo

can add this to the global scope.

However, what is to be done with the wildcard *?

globals()[*] = import_module('path.to.package', '*')

Obviously, the above causes a syntax error.

like image 721
Daryl Avatar asked Jan 25 '14 07:01

Daryl


1 Answers

to do what you want, you need to use "__import__()" and not import_module()

I think this answer can help you

How can I import a package using __import__() when the package name is only known at runtime?

like image 179
archetipo Avatar answered Oct 19 '22 20:10

archetipo