9

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Daryl
  • 1,469
  • 5
  • 18
  • 30
  • Seems similar for sure. – Daryl Jan 25 '14 at 07:08
  • I don't think the second argument to `import_module` means what you think it means. It's the package relative imports should be relative to; none of your examples is a relative import. – user2357112 Jan 25 '14 at 07:09
  • I see. I think I were more trying to use string interpolation to dynamically alter the import path. – Daryl Jan 25 '14 at 07:11
  • This question is answered here: [Python: How to import all methods and attributes from a module dynamically][1] [1]: http://stackoverflow.com/questions/21221358/python-how-to-import-all-methods-and-attributes-from-a-module-dynamically – Daryl Jan 25 '14 at 07:15
  • Hmmm, trying to answer this or mark as a duplicate... – Daryl Jan 25 '14 at 07:16

1 Answers1

1

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?

Community
  • 1
  • 1
archetipo
  • 579
  • 4
  • 10