Python: how to import from all modules in dir?

后端 未结 1 1606
醉酒成梦
醉酒成梦 2020-12-08 08:38

Dir structure:

main.py
my_modules/
   module1.py
   module2.py

module1.py:

class fooBar():
    ....
class pew_pew_FooBarr()         


        
相关标签:
1条回答
  • 2020-12-08 09:16

    In the my_modules folder, add a __init__.py file to make it a proper package. In that file, you can inject the globals of each of those modules in the global scope of the __init__.py file, which makes them available as your module is imported (after you've also added the name of the global to the __all__ variable):

    __all__ = []
    
    import pkgutil
    import inspect
    
    for loader, name, is_pkg in pkgutil.walk_packages(__path__):
        module = loader.find_module(name).load_module(name)
    
        for name, value in inspect.getmembers(module):
            if name.startswith('__'):
                continue
    
            globals()[name] = value
            __all__.append(name)
    

    Now, instead of doing:

    from my_modules.class1 import Stuff
    

    You can just do:

    from my_modules import Stuff
    

    Or to import everything into the global scope, which seems to be what you want to do:

    from my_modules import *
    

    The problem with this approach is classes overwrite one another, so if two modules provide Foo, you'll only be able to use the one that was imported last.

    0 讨论(0)
提交回复
热议问题