Dynamic Importing

Functions for dynamically importing from Python modules.

concoursetools.importing.import_single_class_from_module(file_path, parent_class, class_name=None)[source]

Import the resource class from the module.

Similar to import_classes_from_module(), but ensures only one class is returned.

Parameters:
  • file_path (Path) – The location of the module as a file path.

  • class_name (str | None) – The name of the class to extract. Required if multiple are returned.

  • parent_class (type[object]) – All subclasses of this class defined within the module (not imported from elsewhere) will be extracted.

Return type:

type[object]

Returns:

The extracted class.

Raises:

RuntimeError – If too many or too few classes are available in the module, unless the class name is specified.

concoursetools.importing.import_classes_from_module(file_path, parent_class)[source]

Import all available resource classes from the module.

Parameters:
  • file_path (Path) – The location of the module as a file path.

  • parent_class (type[object]) – All subclasses of this class defined within the module (not imported from elsewhere) will be extracted.

Return type:

dict[str, type[object]]

Returns:

A mapping of class name to class.

concoursetools.importing.file_path_to_import_path(file_path)[source]

Convert a file path to an import path.

Parameters:

file_path (Path) – The path to a Python file.

Raises:

ValueError – If the path doesn’t end in a ‘.py’ extension.

Example:
>>> file_path_to_import_path(Path("module.py"))
'module'
>>> file_path_to_import_path(Path("path/to/module.py"))
'path.to.module'
Return type:

str

concoursetools.importing.import_py_file(import_path, file_path)[source]

Import a .py file as a module.

This is done using a standard Python recipe via importlib.util.

Parameters:
  • import_path (str) – The import path added to sys.modules.

  • file_path (Path) – The path to the .py module.

Return type:

ModuleType

Returns:

The imported module.

Raises:

FileNotFoundError – If the path does not exist.

concoursetools.importing.edit_sys_path(prepend=(), append=())[source]

Temporarily add to sys.path within a context manager.

Parameters:
Seealso:

This is used to enable local imports for the import_py_file().

Return type:

Generator[None]