brails.utils.importer module

Utility classes and methods for the brails module.

Importer([package_name])

Dynamically parses files of a specified package and access its classes.

class brails.utils.importer.Importer(package_name='brails')

Bases: object

Dynamically parses files of a specified package and access its classes.

This class parses a given package directory, identifies all non-abstract classes, and makes them accessible through a dynamic import mechanism. It ensures that class names are unique within the package scope to avoid conflicts. Classes can be retrieved and instantiated by their name using the get_class method.

The Importer class can be imported as below.

from brails import Importer
Parameters:
  • package_path (Path) – The file system path to the root of the package.

  • max_parse_levels (int) – Limits parsing of class files to the first max_parse_levels subdirectories.

  • classes (dict) – A dictionary mapping class names to their module paths.

Raises:
  • NotFoundError – Raised when a package or class is not found, or required keys are missing.

  • BrailsError – Raised when duplicate class names exist across different modules.

get_class(class_name)

Retrieve and import a class by its name.

Parameters:

class_name (str) – The name of the class to retrieve.

Returns:

The class object if found, otherwise raises BrailsError.

Return type:

Any

Raises:

NotFoundError – If the class cannot be found.

Example

>>> from brails import Importer
>>> importer = Importer()
>>> class_obj = importer.get_class(class_name)
get_object(json_object)

Create an instance of a class from JSON object data.

Parameters:

json_object (dict[str, Any]) – A dictionary containing classType and objData keys.

Returns:

An instance of the specified class, initialized with objData.

Return type:

Any

Raises:

NotFoundError – If classType or objData is missing, or if the class is not found.

Example

>>> from brails import Importer
>>> importer = Importer()
>>> obj = importer.get_object({
...     "classType": "MyModel",
...     "objData": {...}
... })