Skip to content

Instantly share code, notes, and snippets.

@Aluriak
Last active July 20, 2021 09:52
Show Gist options
  • Save Aluriak/e2569c58cc8245526aa53dcd0af4dfd4 to your computer and use it in GitHub Desktop.
Save Aluriak/e2569c58cc8245526aa53dcd0af4dfd4 to your computer and use it in GitHub Desktop.
Autoloading of a package submodules in python
def autoload_package_submodules(package:object, log_info:callable=print, log_error:callable=print):
"""Import all submodules of given package to have them loaded"""
import os, glob, importlib
path = os.path.split(package.__file__)[0]
pkg_name = package.__name__
for fname in glob.glob(os.path.join(path, '*.py')):
modname = os.path.splitext(os.path.split(fname)[1])[0]
if modname.startswith('_'): continue # ignore private modules
try:
module = importlib.import_module(pkg_name + '.' + modname)
except Exception as err:
log_error(f"{modname} couldn't be loaded because of a raised {repr(err)}")
else:
setattr(package, modname, module)
log_info(f"module {modname} loaded as {pkg_name}.{modname}")
# usage example
import osgeo_utils # coming from the GDAL library
autoload_package_submodules(osgeo_utils)
# now osgeo_utils has all its inner submodules imported.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment