Search code examples
pythonmodulepackagepython-importlib

Python, Importlib. Imitation of "from module import * "


How to imitate from module import * with importlib. I know that you can do:

from importlib.machinery import SourceFileLoader
module = SourceFileLoader('module.py', os.path.join(CWD,'module.py')).load_module()

module.executeFunction()

Is there any way to import module so that we can do executeFunction() without writing module.executeFunction()


Solution

  • I don't see this as a good idea, keeping things in objects is definitely the better way to go, but if you so needed to...

    for func in [func for func in module.__dict__ if not func.startswith("_")]:
        vars()[func] = module.__dict__[func]
    

    Leaving out the functions that start with _ is probably a good idea because of builtins, but you can exclude that if you so wish.