Python 3.5+: How to dynamically import a module given the full file path (in the presence of implicit sibling imports)?

The easiest solution I could come up with is to temporarily modify sys.path in the function doing the import: from contextlib import contextmanager @contextmanager def add_to_path(p): import sys old_path = sys.path sys.path = sys.path[:] sys.path.insert(0, p) try: yield finally: sys.path = old_path def path_import(absolute_path): ”’implementation taken from https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly”’ with add_to_path(os.path.dirname(absolute_path)): spec = importlib.util.spec_from_file_location(absolute_path, absolute_path) module … Read more

Import class from module dynamically

It is expecting my_module to be a package containing a module named ‘my_class’. If you need to import a class, or an attribute in general, dynamically, just use getattr after you import the module: cls = getattr(import_module(‘my_module’), ‘my_class’) Also, yes, it does only work with modules. Remember importlib.import_module is a wrapper of the internal importlib.__import__ … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)