Skip to content

importer ¤

This module contains utilities to dynamically import objects.

Functions:

dynamic_import ¤

dynamic_import(
    import_path: str,
    import_paths: Sequence[str | Path] | None = None,
) -> Any

Dynamically import the specified object.

It can be a module, class, method, function, attribute, nested arbitrarily.

It works like this:

  • for a given object path a.b.x.y
  • it tries to import a.b.x.y as a module (with importlib.import_module)
  • if it fails, it tries again with a.b.x, storing y
  • then a.b, storing x.y
  • then a, storing b.x.y
  • if nothing worked, it raises an error
  • if one of the iteration worked, it moves on, and...
  • it tries to get the remaining (stored) parts with getattr
  • for example it gets b from a, then x from b, etc.
  • if a single attribute access fails, it raises an error
  • if everything worked, it returns the last obtained attribute

Since the function potentially tries multiple things before succeeding, all errors happening along the way are recorded, and re-emitted with an ImportError when it fails, to let users know what was tried.

Important

The paths given through the import_paths parameter are used to temporarily patch sys.path: this function is therefore not thread-safe.

Important

The paths given as import_paths must be correct. The contents of sys.path must be consistent to what a user of the imported code would expect. Given a set of paths, if the import fails for a user, it will fail here too, with potentially unintuitive errors. If we wanted to make this function more robust, we could add a loop to "roll the window" of given paths, shifting them to the left (for example: ("/a/a", "/a/b", "/a/c/"), then ("/a/b", "/a/c", "/a/a/"), then ("/a/c", "/a/a", "/a/b/")), to make sure each entry is given highest priority at least once, maintaining relative order, but we deem this unncessary for now.

Parameters:

  • import_path (str) –

    The path of the object to import.

  • import_paths (Sequence[str | Path] | None, default: None ) –

    The (sys) paths to import the object from.

Raises:

  • ModuleNotFoundError

    When the object's module could not be found.

  • ImportError

    When there was an import error or when couldn't get the attribute.

Returns:

  • Any

    The imported object.

sys_path ¤

sys_path(*paths: str | Path) -> Iterator[None]

Redefine sys.path temporarily.

Parameters:

  • *paths (str | Path, default: () ) –

    The paths to use when importing modules. If no paths are given, keep sys.path untouched.

Yields: