How does one do the equivalent of “import * from module” with Python's __import__ function?

前端 未结 5 760
温柔的废话
温柔的废话 2020-11-29 03:51

Given a string with a module name, how do you import everything in the module as if you had called:

from module import *

i.e. given string

5条回答
  •  Happy的楠姐
    2020-11-29 04:54

    The underlying problem is that I am developing some Django, but on more than one host (with colleagues), all with different settings. I was hoping to do something like this in the project/settings.py file:

    from platform import node
    
    settings_files = { 'BMH.lan': 'settings_bmh.py", ... } 
    
    __import__( settings_files[ node() ] )
    

    It seemed a simple solution (thus elegant), but I would agree that it has a smell to it and the simplicity goes out the loop when you have to use logic like what John Millikin posted (thanks). Here's essentially the solution I went with:

    from platform import node
    
    from settings_global import *
    
    n = node()
    
    if n == 'BMH.lan':
      from settings_bmh import *
    # add your own, here...
    else:
      raise Exception("No host settings for '%s'. See settings.py." % node())
    

    Which works fine for our purposes.

提交回复
热议问题