How to import all submodules?

前端 未结 9 1401
盖世英雄少女心
盖世英雄少女心 2020-11-27 16:57

I have a directory structure as follows:

| main.py
| scripts
|--| __init__.py
   | script1.py
   | script2.py
   | script3.py

From ma

9条回答
  •  我在风中等你
    2020-11-27 17:38

    I got tired of this problem myself, so I wrote a package called automodinit to fix it. You can get it from http://pypi.python.org/pypi/automodinit/. Usage is like this:

    1. Include the automodinit package into your setup.py dependencies.
    2. Add the following to the beginning of the __init__.py file:
    __all__ = ["I will get rewritten"]
    # Don't modify the line above, or this line!
    import automodinit
    automodinit.automodinit(__name__, __file__, globals())
    del automodinit
    # Anything else you want can go after here, it won't get modified.
    

    That's it! From now on importing a module will set __all__ to a list of .py[co] files in the module and will also import each of those files as though you had typed:

    for x in __all__: import x
    

    Therefore the effect of from M import * matches exactly import M.

    automodinit is happy running from inside ZIP archives and is therefore ZIP safe.

提交回复
热议问题