Skip to content

Plugins

framework3.base.base_clases.BasePlugin

Bases: ABC

Base class for all plugins in the framework.

This abstract class provides core functionality for attribute management, serialization, and type checking. It serves as the foundation for all plugin types in the framework, ensuring consistent behavior and interfaces.

Key Features
  • Automatic separation of public and private attributes
  • Type checking for methods using typeguard
  • Inheritance of type annotations from abstract methods
  • JSON serialization and deserialization
  • Rich representation for debugging
Usage

To create a new plugin type, inherit from this class and implement the required methods. For example:

class MyCustomPlugin(BasePlugin):
    def __init__(self, param1: int, param2: str):
        super().__init__(param1=param1, param2=param2)

    def my_method(self):
        # Custom implementation
        pass

Attributes:

Name Type Description
_public_attributes dict

A dictionary containing all public attributes of the plugin.

_private_attributes dict

A dictionary containing all private attributes of the plugin.

Methods:

Name Description
__new__

Creates a new instance of the plugin and applies type checking.

__init__

Initializes the plugin instance, separating public and private attributes.

model_dump

Returns a copy of the public attributes.

dict

Alias for model_dump.

json

Returns a JSON-encodable representation of the public attributes.

item_dump

Returns a dictionary representation of the plugin, including its class name and parameters.

get_extra

Returns a copy of the private attributes.

model_validate

Validates and creates an instance from a dictionary.

Note

This class uses the ABC (Abstract Base Class) to define an interface that all plugins must adhere to. It also leverages Python's type hinting and the typeguard library for runtime type checking.

Source code in framework3/base/base_clases.py
class BasePlugin(ABC):
    """
    Base class for all plugins in the framework.

    This abstract class provides core functionality for attribute management,
    serialization, and type checking. It serves as the foundation for all plugin
    types in the framework, ensuring consistent behavior and interfaces.

    Key Features:
        - Automatic separation of public and private attributes
        - Type checking for methods using typeguard
        - Inheritance of type annotations from abstract methods
        - JSON serialization and deserialization
        - Rich representation for debugging

    Usage:
        To create a new plugin type, inherit from this class and implement
        the required methods. For example:

        ```python
        class MyCustomPlugin(BasePlugin):
            def __init__(self, param1: int, param2: str):
                super().__init__(param1=param1, param2=param2)

            def my_method(self):
                # Custom implementation
                pass
        ```

    Attributes:
        _public_attributes (dict): A dictionary containing all public attributes of the plugin.
        _private_attributes (dict): A dictionary containing all private attributes of the plugin.

    Methods:
        __new__(cls, *args, **kwargs):
            Creates a new instance of the plugin and applies type checking.

        __init__(**kwargs):
            Initializes the plugin instance, separating public and private attributes.

        model_dump(**kwargs) -> dict:
            Returns a copy of the public attributes.

        dict(**kwargs) -> dict:
            Alias for model_dump.

        json(**kwargs) -> dict:
            Returns a JSON-encodable representation of the public attributes.

        item_dump(include=[], **kwargs) -> Dict[str, Any]:
            Returns a dictionary representation of the plugin, including its class name and parameters.

        get_extra() -> Dict[str, Any]:
            Returns a copy of the private attributes.

        model_validate(obj) -> BasePlugin:
            Validates and creates an instance from a dictionary.

    Note:
        This class uses the ABC (Abstract Base Class) to define an interface
        that all plugins must adhere to. It also leverages Python's type hinting
        and the typeguard library for runtime type checking.
    """

    def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self:
        """
        Create a new instance of the BasePlugin class.

        This method applies type checking to the __init__ method and all other methods,
        and inherits type annotations from abstract methods in parent classes.

        Args:
            *args Any: Variable length argument list.
            **kwargs Any: Arbitrary keyword arguments.

        Returns:
            BasePlugin: A new instance of the BasePlugin class.
        """
        instance = super().__new__(cls)

        # Obtener la firma del método __init__
        init_signature = inspect.signature(cls.__init__)

        instance.__dict__["_public_attributes"] = {
            k: v
            for k, v in kwargs.items()
            if not k.startswith("_") and k in init_signature.parameters
        }
        instance.__dict__["_private_attributes"] = {
            k: v
            for k, v in kwargs.items()
            if k.startswith("_") and k in init_signature.parameters
        }

        # Apply typechecked to the __init__ method
        init_method = cls.__init__
        if init_method is not object.__init__:
            cls.__init__ = typechecked(init_method)  # type: ignore[method-assign]

        # Inherit type annotations from abstract methods
        cls.__inherit_annotations()

        # Apply typechecked to all methods defined in the class
        for attr_name, attr_value in cls.__dict__.items():
            if inspect.isfunction(attr_value) and attr_name != "__init__":
                setattr(cls, attr_name, typechecked(attr_value))

        return instance

    @classmethod
    def __inherit_annotations(cls):
        """
        Inherit type annotations from abstract methods in parent classes.

        This method is responsible for combining type annotations from abstract methods
        in parent classes with those in the concrete methods of the current class.
        This ensures that type hints are properly inherited and can be used for
        type checking and documentation purposes.

        Args:
            cls (type): The class on which this method is called.

        Note:
            This method modifies the `__annotations__` attribute of concrete methods
            in the class, combining them with annotations from corresponding abstract
            methods in parent classes.
        """
        for base in cls.__bases__:
            for name, method in base.__dict__.items():
                if getattr(method, "__isabstractmethod__", False):
                    if hasattr(cls, name):
                        concrete_method = getattr(cls, name)
                        abstract_annotations = get_type_hints(method)
                        concrete_annotations = get_type_hints(concrete_method)
                        combined_annotations = {
                            **abstract_annotations,
                            **concrete_annotations,
                        }
                        setattr(
                            concrete_method, "__annotations__", combined_annotations
                        )

    def __init__(self, **kwargs: Any):
        """
        Initialize the BasePlugin instance.

        This method separates public and private attributes based on their naming.

        Args:
            **kwargs (Any): Arbitrary keyword arguments that will be stored as attributes.
        """
        self.__dict__["_public_attributes"] = {
            k: v for k, v in kwargs.items() if not k.startswith("_")
        }
        self.__dict__["_private_attributes"] = {
            k: v for k, v in kwargs.items() if k.startswith("_")
        }

    def __getattr__(self, name: str) -> Any:
        """
        Custom attribute getter that checks both public and private attribute dictionaries.

        Args:
            name (str): The name of the attribute to retrieve.

        Returns:
            Any: The value of the requested attribute.

        Raises:
            AttributeError: If the attribute is not found in either public or private dictionaries.
        """
        if name in self.__dict__.get("_public_attributes", {}):
            return self.__dict__["_public_attributes"][name]
        elif name in self.__dict__.get("_private_attributes", {}):
            return self.__dict__["_private_attributes"][name]
        raise AttributeError(
            f"'{self.__class__.__name__}' object has no attribute '{name}'"
        )

    def __setattr__(self, name: str, value: Any):
        """
        Custom attribute setter that separates public and private attributes.

        Args:
            name (str): The name of the attribute to set.
            value (Any): The value to assign to the attribute.
        """
        if not hasattr(self, "_private_attributes"):
            # During initialization, attributes go directly to __dict__
            super().__setattr__(name, value)
        else:
            if name.startswith("_"):
                self.__dict__["_private_attributes"][name] = value
            else:
                self.__dict__["_public_attributes"][name] = value
            super().__setattr__(name, value)

    def __repr__(self) -> str:
        """
        String representation of the plugin, showing its class name and public attributes.

        Returns:
            str: A string representation of the plugin.
        """
        return f"{self.__class__.__name__}({self._public_attributes})"

    def model_dump(self, **kwargs: Any) -> Dict[str, Any]:
        """
        Return a copy of the public attributes.

        Args:
            **kwargs (Any): Additional keyword arguments (not used in this method).

        Returns:
            Dict[str, Any]: A copy of the public attributes.
        """
        return self._public_attributes.copy()

    def dict(self, **kwargs: Any) -> Dict[str, Any]:
        """
        Alias for model_dump.

        Args:
            **kwargs (Any): Additional keyword arguments passed to model_dump.

        Returns:
            Dict[str, Any]: A copy of the public attributes.
        """
        return self.model_dump(**kwargs)

    def json(self, **kwargs: Any) -> Dict[str, Any]:
        """
        Return a JSON-encodable representation of the public attributes.

        Args:
            **kwargs (Any): Additional keyword arguments passed to jsonable_encoder.

        Returns:
            Dict[str, Any]: A JSON-encodable representation of the public attributes.
        """
        return jsonable_encoder(self._public_attributes, **kwargs)

    def item_dump(self, include=[], **kwargs: Any) -> Dict[str, Any]:
        """
        Return a dictionary representation of the plugin, including its class name and parameters.

        Args:
            include (list): A list of private attributes to include in the dump.
            **kwargs (Any): Additional keyword arguments passed to jsonable_encoder.

        Returns:
            Dict[str, Any]: A dictionary representation of the plugin.
        """
        included = {k: v for k, v in self._private_attributes.items() if k in include}
        dump = {
            "clazz": self.__class__.__name__,
            "params": jsonable_encoder(
                self._public_attributes,
                custom_encoder={
                    BasePlugin: lambda v: v.item_dump(include=include, **kwargs),
                    type: lambda v: {"clazz": v.__name__},
                    np.integer: lambda x: int(x),
                    np.floating: lambda x: float(x),
                },
                **kwargs,
            ),
        }
        if include != []:
            dump.update(
                **jsonable_encoder(
                    included,
                    custom_encoder={
                        BasePlugin: lambda v: v.item_dump(include=include, **kwargs),
                        type: lambda v: {"clazz": v.__name__},
                        np.integer: lambda x: int(x),
                        np.floating: lambda x: float(x),
                    },
                    **kwargs,
                )
            )

        return dump

    def get_extra(self) -> Dict[str, Any]:
        """
        Return a copy of the private attributes.

        Returns:
            Dict[str, Any]: A copy of the private attributes.
        """
        return self._private_attributes.copy()

    def __getstate__(self) -> Dict[str, Any]:
        """
        Prepare the object for pickling.

        Returns:
            Dict[str, Any]: A copy of the object's __dict__.
        """
        state = self.__dict__.copy()
        return state

    def __setstate__(self, state: Dict[str, Any]):
        """
        Restore the object from its pickled state.

        Args:
            state (Dict[str, Any]): The pickled state of the object.
        """
        self.__dict__.update(state)

    @classmethod
    def model_validate(cls, obj: object) -> BasePlugin:
        """
        Validate and create an instance from a dictionary.

        Args:
            obj (Object): The object to validate and create an instance from.

        Returns:
            BasePlugin: An instance of the class.

        Raises:
            ValueError: If the input is not a dictionary.
        """
        if isinstance(obj, dict):
            return cls(**obj)
        raise ValueError(f"Cannot validate {type(obj)}")

    def __rich_repr__(self) -> Generator[Any, Any, Any]:
        """
        Rich representation of the plugin, used by the rich library.

        Yields:
            Generator[Any, Any, Any]: Key-value pairs of public attributes.
        """
        for key, value in self._public_attributes.items():
            yield key, value

    @staticmethod
    def build_from_dump(
        dump_dict: Dict[str, Any], factory: BaseFactory[BasePlugin]
    ) -> BasePlugin | Type[BasePlugin]:
        """
        Reconstruct a plugin instance from a dumped dictionary representation.

        This method handles nested plugin structures and uses a factory to create instances.

        Args:
            dump_dict (Dict[str, Any]): The dumped dictionary representation of the plugin.
            factory (BaseFactory[BasePlugin]): A factory for creating plugin instances.

        Returns:
            BasePlugin | Type[BasePlugin]: The reconstructed plugin instance or class.
        """
        level_clazz: Type[BasePlugin] = factory[dump_dict["clazz"]]

        if "params" in dump_dict:
            level_params: Dict[str, Any] = {}
            for k, v in dump_dict["params"].items():
                if isinstance(v, dict):
                    if "clazz" in v:
                        level_params[k] = BasePlugin.build_from_dump(v, factory)
                    else:
                        level_params[k] = v
                elif isinstance(v, list):
                    level_params[k] = [
                        BasePlugin.build_from_dump(i, factory) for i in v
                    ]
                else:
                    level_params[k] = v
            return level_clazz(**level_params)
        else:
            return level_clazz

__getattr__(name)

Custom attribute getter that checks both public and private attribute dictionaries.

Parameters:

Name Type Description Default
name str

The name of the attribute to retrieve.

required

Returns:

Name Type Description
Any Any

The value of the requested attribute.

Raises:

Type Description
AttributeError

If the attribute is not found in either public or private dictionaries.

Source code in framework3/base/base_clases.py
def __getattr__(self, name: str) -> Any:
    """
    Custom attribute getter that checks both public and private attribute dictionaries.

    Args:
        name (str): The name of the attribute to retrieve.

    Returns:
        Any: The value of the requested attribute.

    Raises:
        AttributeError: If the attribute is not found in either public or private dictionaries.
    """
    if name in self.__dict__.get("_public_attributes", {}):
        return self.__dict__["_public_attributes"][name]
    elif name in self.__dict__.get("_private_attributes", {}):
        return self.__dict__["_private_attributes"][name]
    raise AttributeError(
        f"'{self.__class__.__name__}' object has no attribute '{name}'"
    )

__getstate__()

Prepare the object for pickling.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A copy of the object's dict.

Source code in framework3/base/base_clases.py
def __getstate__(self) -> Dict[str, Any]:
    """
    Prepare the object for pickling.

    Returns:
        Dict[str, Any]: A copy of the object's __dict__.
    """
    state = self.__dict__.copy()
    return state

__inherit_annotations() classmethod

Inherit type annotations from abstract methods in parent classes.

This method is responsible for combining type annotations from abstract methods in parent classes with those in the concrete methods of the current class. This ensures that type hints are properly inherited and can be used for type checking and documentation purposes.

Parameters:

Name Type Description Default
cls type

The class on which this method is called.

required
Note

This method modifies the __annotations__ attribute of concrete methods in the class, combining them with annotations from corresponding abstract methods in parent classes.

Source code in framework3/base/base_clases.py
@classmethod
def __inherit_annotations(cls):
    """
    Inherit type annotations from abstract methods in parent classes.

    This method is responsible for combining type annotations from abstract methods
    in parent classes with those in the concrete methods of the current class.
    This ensures that type hints are properly inherited and can be used for
    type checking and documentation purposes.

    Args:
        cls (type): The class on which this method is called.

    Note:
        This method modifies the `__annotations__` attribute of concrete methods
        in the class, combining them with annotations from corresponding abstract
        methods in parent classes.
    """
    for base in cls.__bases__:
        for name, method in base.__dict__.items():
            if getattr(method, "__isabstractmethod__", False):
                if hasattr(cls, name):
                    concrete_method = getattr(cls, name)
                    abstract_annotations = get_type_hints(method)
                    concrete_annotations = get_type_hints(concrete_method)
                    combined_annotations = {
                        **abstract_annotations,
                        **concrete_annotations,
                    }
                    setattr(
                        concrete_method, "__annotations__", combined_annotations
                    )

__init__(**kwargs)

Initialize the BasePlugin instance.

This method separates public and private attributes based on their naming.

Parameters:

Name Type Description Default
**kwargs Any

Arbitrary keyword arguments that will be stored as attributes.

{}
Source code in framework3/base/base_clases.py
def __init__(self, **kwargs: Any):
    """
    Initialize the BasePlugin instance.

    This method separates public and private attributes based on their naming.

    Args:
        **kwargs (Any): Arbitrary keyword arguments that will be stored as attributes.
    """
    self.__dict__["_public_attributes"] = {
        k: v for k, v in kwargs.items() if not k.startswith("_")
    }
    self.__dict__["_private_attributes"] = {
        k: v for k, v in kwargs.items() if k.startswith("_")
    }

__new__(*args, **kwargs)

Create a new instance of the BasePlugin class.

This method applies type checking to the init method and all other methods, and inherits type annotations from abstract methods in parent classes.

Parameters:

Name Type Description Default
*args Any

Variable length argument list.

()
**kwargs Any

Arbitrary keyword arguments.

{}

Returns:

Name Type Description
BasePlugin Self

A new instance of the BasePlugin class.

Source code in framework3/base/base_clases.py
def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self:
    """
    Create a new instance of the BasePlugin class.

    This method applies type checking to the __init__ method and all other methods,
    and inherits type annotations from abstract methods in parent classes.

    Args:
        *args Any: Variable length argument list.
        **kwargs Any: Arbitrary keyword arguments.

    Returns:
        BasePlugin: A new instance of the BasePlugin class.
    """
    instance = super().__new__(cls)

    # Obtener la firma del método __init__
    init_signature = inspect.signature(cls.__init__)

    instance.__dict__["_public_attributes"] = {
        k: v
        for k, v in kwargs.items()
        if not k.startswith("_") and k in init_signature.parameters
    }
    instance.__dict__["_private_attributes"] = {
        k: v
        for k, v in kwargs.items()
        if k.startswith("_") and k in init_signature.parameters
    }

    # Apply typechecked to the __init__ method
    init_method = cls.__init__
    if init_method is not object.__init__:
        cls.__init__ = typechecked(init_method)  # type: ignore[method-assign]

    # Inherit type annotations from abstract methods
    cls.__inherit_annotations()

    # Apply typechecked to all methods defined in the class
    for attr_name, attr_value in cls.__dict__.items():
        if inspect.isfunction(attr_value) and attr_name != "__init__":
            setattr(cls, attr_name, typechecked(attr_value))

    return instance

__repr__()

String representation of the plugin, showing its class name and public attributes.

Returns:

Name Type Description
str str

A string representation of the plugin.

Source code in framework3/base/base_clases.py
def __repr__(self) -> str:
    """
    String representation of the plugin, showing its class name and public attributes.

    Returns:
        str: A string representation of the plugin.
    """
    return f"{self.__class__.__name__}({self._public_attributes})"

__rich_repr__()

Rich representation of the plugin, used by the rich library.

Yields:

Type Description
Any

Generator[Any, Any, Any]: Key-value pairs of public attributes.

Source code in framework3/base/base_clases.py
def __rich_repr__(self) -> Generator[Any, Any, Any]:
    """
    Rich representation of the plugin, used by the rich library.

    Yields:
        Generator[Any, Any, Any]: Key-value pairs of public attributes.
    """
    for key, value in self._public_attributes.items():
        yield key, value

__setattr__(name, value)

Custom attribute setter that separates public and private attributes.

Parameters:

Name Type Description Default
name str

The name of the attribute to set.

required
value Any

The value to assign to the attribute.

required
Source code in framework3/base/base_clases.py
def __setattr__(self, name: str, value: Any):
    """
    Custom attribute setter that separates public and private attributes.

    Args:
        name (str): The name of the attribute to set.
        value (Any): The value to assign to the attribute.
    """
    if not hasattr(self, "_private_attributes"):
        # During initialization, attributes go directly to __dict__
        super().__setattr__(name, value)
    else:
        if name.startswith("_"):
            self.__dict__["_private_attributes"][name] = value
        else:
            self.__dict__["_public_attributes"][name] = value
        super().__setattr__(name, value)

__setstate__(state)

Restore the object from its pickled state.

Parameters:

Name Type Description Default
state Dict[str, Any]

The pickled state of the object.

required
Source code in framework3/base/base_clases.py
def __setstate__(self, state: Dict[str, Any]):
    """
    Restore the object from its pickled state.

    Args:
        state (Dict[str, Any]): The pickled state of the object.
    """
    self.__dict__.update(state)

build_from_dump(dump_dict, factory) staticmethod

Reconstruct a plugin instance from a dumped dictionary representation.

This method handles nested plugin structures and uses a factory to create instances.

Parameters:

Name Type Description Default
dump_dict Dict[str, Any]

The dumped dictionary representation of the plugin.

required
factory BaseFactory[BasePlugin]

A factory for creating plugin instances.

required

Returns:

Type Description
BasePlugin | Type[BasePlugin]

BasePlugin | Type[BasePlugin]: The reconstructed plugin instance or class.

Source code in framework3/base/base_clases.py
@staticmethod
def build_from_dump(
    dump_dict: Dict[str, Any], factory: BaseFactory[BasePlugin]
) -> BasePlugin | Type[BasePlugin]:
    """
    Reconstruct a plugin instance from a dumped dictionary representation.

    This method handles nested plugin structures and uses a factory to create instances.

    Args:
        dump_dict (Dict[str, Any]): The dumped dictionary representation of the plugin.
        factory (BaseFactory[BasePlugin]): A factory for creating plugin instances.

    Returns:
        BasePlugin | Type[BasePlugin]: The reconstructed plugin instance or class.
    """
    level_clazz: Type[BasePlugin] = factory[dump_dict["clazz"]]

    if "params" in dump_dict:
        level_params: Dict[str, Any] = {}
        for k, v in dump_dict["params"].items():
            if isinstance(v, dict):
                if "clazz" in v:
                    level_params[k] = BasePlugin.build_from_dump(v, factory)
                else:
                    level_params[k] = v
            elif isinstance(v, list):
                level_params[k] = [
                    BasePlugin.build_from_dump(i, factory) for i in v
                ]
            else:
                level_params[k] = v
        return level_clazz(**level_params)
    else:
        return level_clazz

dict(**kwargs)

Alias for model_dump.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments passed to model_dump.

{}

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A copy of the public attributes.

Source code in framework3/base/base_clases.py
def dict(self, **kwargs: Any) -> Dict[str, Any]:
    """
    Alias for model_dump.

    Args:
        **kwargs (Any): Additional keyword arguments passed to model_dump.

    Returns:
        Dict[str, Any]: A copy of the public attributes.
    """
    return self.model_dump(**kwargs)

get_extra()

Return a copy of the private attributes.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A copy of the private attributes.

Source code in framework3/base/base_clases.py
def get_extra(self) -> Dict[str, Any]:
    """
    Return a copy of the private attributes.

    Returns:
        Dict[str, Any]: A copy of the private attributes.
    """
    return self._private_attributes.copy()

item_dump(include=[], **kwargs)

Return a dictionary representation of the plugin, including its class name and parameters.

Parameters:

Name Type Description Default
include list

A list of private attributes to include in the dump.

[]
**kwargs Any

Additional keyword arguments passed to jsonable_encoder.

{}

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary representation of the plugin.

Source code in framework3/base/base_clases.py
def item_dump(self, include=[], **kwargs: Any) -> Dict[str, Any]:
    """
    Return a dictionary representation of the plugin, including its class name and parameters.

    Args:
        include (list): A list of private attributes to include in the dump.
        **kwargs (Any): Additional keyword arguments passed to jsonable_encoder.

    Returns:
        Dict[str, Any]: A dictionary representation of the plugin.
    """
    included = {k: v for k, v in self._private_attributes.items() if k in include}
    dump = {
        "clazz": self.__class__.__name__,
        "params": jsonable_encoder(
            self._public_attributes,
            custom_encoder={
                BasePlugin: lambda v: v.item_dump(include=include, **kwargs),
                type: lambda v: {"clazz": v.__name__},
                np.integer: lambda x: int(x),
                np.floating: lambda x: float(x),
            },
            **kwargs,
        ),
    }
    if include != []:
        dump.update(
            **jsonable_encoder(
                included,
                custom_encoder={
                    BasePlugin: lambda v: v.item_dump(include=include, **kwargs),
                    type: lambda v: {"clazz": v.__name__},
                    np.integer: lambda x: int(x),
                    np.floating: lambda x: float(x),
                },
                **kwargs,
            )
        )

    return dump

json(**kwargs)

Return a JSON-encodable representation of the public attributes.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments passed to jsonable_encoder.

{}

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A JSON-encodable representation of the public attributes.

Source code in framework3/base/base_clases.py
def json(self, **kwargs: Any) -> Dict[str, Any]:
    """
    Return a JSON-encodable representation of the public attributes.

    Args:
        **kwargs (Any): Additional keyword arguments passed to jsonable_encoder.

    Returns:
        Dict[str, Any]: A JSON-encodable representation of the public attributes.
    """
    return jsonable_encoder(self._public_attributes, **kwargs)

model_dump(**kwargs)

Return a copy of the public attributes.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments (not used in this method).

{}

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A copy of the public attributes.

Source code in framework3/base/base_clases.py
def model_dump(self, **kwargs: Any) -> Dict[str, Any]:
    """
    Return a copy of the public attributes.

    Args:
        **kwargs (Any): Additional keyword arguments (not used in this method).

    Returns:
        Dict[str, Any]: A copy of the public attributes.
    """
    return self._public_attributes.copy()

model_validate(obj) classmethod

Validate and create an instance from a dictionary.

Parameters:

Name Type Description Default
obj Object

The object to validate and create an instance from.

required

Returns:

Name Type Description
BasePlugin BasePlugin

An instance of the class.

Raises:

Type Description
ValueError

If the input is not a dictionary.

Source code in framework3/base/base_clases.py
@classmethod
def model_validate(cls, obj: object) -> BasePlugin:
    """
    Validate and create an instance from a dictionary.

    Args:
        obj (Object): The object to validate and create an instance from.

    Returns:
        BasePlugin: An instance of the class.

    Raises:
        ValueError: If the input is not a dictionary.
    """
    if isinstance(obj, dict):
        return cls(**obj)
    raise ValueError(f"Cannot validate {type(obj)}")