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.

Attributes:
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.

Methods:
get_object(json_object: Dict[str, Any]) -> Any:

Creates an object instance from a dictionary containing class type and data.

get_class(class_name: str) -> Any:

Retrieves a class by name from the package and returns the class object.

__repr__() -> str:

Returns a human-readable summary of available classes and their modules.

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.

Example:
>>> importer = Importer("brails")
>>> obj = importer.get_object({
...     "classType": "MyModel",
...     "objData": {...}
... })
get_class(class_name: str) Any

Retrieve and import a class by its name.

Args:
class_name (str):

The name of the class to retrieve.

Returns:
Any:

The class object if found, otherwise raises BrailsError.

Raises:
NotFoundError:

If the class cannot be found.

get_object(json_object: Dict[str, Any]) Any

Create an instance of a class from JSON object data.

Args:
json_object (dict[str, Any]):

A dictionary containing “classType” and “objData” keys.

Returns:
Any:

An instance of the specified class, initialized with objData.

Raises:
NotFoundError:

If “classType” or “objData” is missing, or if the class is not found.