How to load all modules in a folder?

List all python (.py) files in the current folder and put them as __all__ variable in __init__.py from os.path import dirname, basename, isfile, join import glob modules = glob.glob(join(dirname(__file__), “*.py”)) __all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith(‘__init__.py’)]

Sibling package imports

Tired of sys.path hacks? There are plenty of sys.path.append -hacks available, but I found an alternative way of solving the problem in hand. Summary Wrap the code into one folder (e.g. packaged_stuff) Create setup.py script where you use setuptools.setup(). (see minimal setup.py below) Pip install the package in editable state with pip install -e <myproject_folder> … Read more

How to fix “Attempted relative import in non-package” even with __init__.py

To elaborate on Ignacio Vazquez-Abrams’s answer: The Python import mechanism works relative to the __name__ of the current file. When you execute a file directly, it doesn’t have its usual name, but has “__main__” as its name instead. So relative imports don’t work. You can, as Igancio suggested, execute it using the -m option. If … Read more