Skip to content

Unit

Unit - Data management in dynamic fields.

Unit

Unit of information for choices parameter in dynamic field types.

Source code in src/ramifice/unit.py
class Unit:
    """Unit of information for `choices` parameter in dynamic field types."""

    def __init__(
        self,
        field: str,
        title: dict[str, str],  # Example: {"en": "Title", "ru": "Заголовок"}
        value: float | int | str,
        is_delete: bool = False,
    ) -> None:
        """Unit of information for `choices` parameter in dynamic field types.

        Args:
            field: The name of the dynamic field.
            title: The name of the choice item. Example: {"en": "Title", "ru": "Заголовок"}.
            value: The value of the choice item.
            is_delete: True - if you need to remove the item of choice.
        """
        # Check the match of types.
        if not isinstance(field, str):
            err_msg = "Class: `Unit` > Argument: `field` => Not а `str` type!"
            logger.critical(err_msg)
            raise PanicError(err_msg)
        if not isinstance(title, dict):
            err_msg = (
                "Class: `Unit` > Argument: `title` => Not а `str` type! "
                + 'Example: {"en": "Title", "ru": "Заголовок"}'
            )
            logger.critical(err_msg)
            raise PanicError(err_msg)
        if not isinstance(value, (float, int, str)):
            err_msg = "Class: `Unit` > Argument: `value` => Not a `float | int | str` type!"
            logger.critical(err_msg)
            raise PanicError(err_msg)
        if not isinstance(is_delete, bool):
            err_msg = "Class: `Unit` > Argument: `is_delete` => Not a `bool` type!"
            logger.critical(err_msg)
            raise PanicError(err_msg)

        self.field = field
        self.title = title
        self.value = value
        self.is_delete = is_delete

        self.check_empty_arguments()

    def check_empty_arguments(self) -> None:
        """Check the arguments (field|title|value) for empty values.

        Returns:
            `None`
        """
        field_name: str = ""

        if len(self.field) == 0:
            field_name = "field"
        elif len(self.title) == 0:
            field_name = "title"
        elif isinstance(self.value, str) and len(self.value) == 0:
            field_name = "value"

        if len(field_name) > 0:
            err_msg = (
                "Method: `unit_manager` > "
                + "Argument: `unit` > "
                + f"Field: `{field_name}` => "
                + "Must not be empty!"
            )
            logger.critical(err_msg)
            raise PanicError(err_msg)

    def to_dict(self) -> dict[str, Any]:
        """Convert Unit instance to a dictionary."""
        unit_dict: dict[str, Any] = {}
        for key, value in self.__dict__.items():
            if not isinstance(value, Callable):
                unit_dict[key] = value
        return unit_dict

    def to_json(self) -> str:
        """Convert Unit instance to a JSON-string."""
        return orjson.dumps(self.to_dict()).decode("utf-8")

    @classmethod
    def from_dict(cls: Any, unit_dict: dict[str, float | int | str | bool]) -> Any:
        """Convert Unit-dictionary to a Unit instance."""
        return cls(**unit_dict)

    @classmethod
    def from_json(cls: Any, json_str: str) -> Any:
        """Convert JSON-string to Unit instance."""
        unit_dict = orjson.loads(json_str)
        return cls.from_dict(unit_dict)

__init__(field, title, value, is_delete=False)

Unit of information for choices parameter in dynamic field types.

Parameters:

Name Type Description Default
field str

The name of the dynamic field.

required
title dict[str, str]

The name of the choice item. Example: {"en": "Title", "ru": "Заголовок"}.

required
value float | int | str

The value of the choice item.

required
is_delete bool

True - if you need to remove the item of choice.

False
Source code in src/ramifice/unit.py
def __init__(
    self,
    field: str,
    title: dict[str, str],  # Example: {"en": "Title", "ru": "Заголовок"}
    value: float | int | str,
    is_delete: bool = False,
) -> None:
    """Unit of information for `choices` parameter in dynamic field types.

    Args:
        field: The name of the dynamic field.
        title: The name of the choice item. Example: {"en": "Title", "ru": "Заголовок"}.
        value: The value of the choice item.
        is_delete: True - if you need to remove the item of choice.
    """
    # Check the match of types.
    if not isinstance(field, str):
        err_msg = "Class: `Unit` > Argument: `field` => Not а `str` type!"
        logger.critical(err_msg)
        raise PanicError(err_msg)
    if not isinstance(title, dict):
        err_msg = (
            "Class: `Unit` > Argument: `title` => Not а `str` type! "
            + 'Example: {"en": "Title", "ru": "Заголовок"}'
        )
        logger.critical(err_msg)
        raise PanicError(err_msg)
    if not isinstance(value, (float, int, str)):
        err_msg = "Class: `Unit` > Argument: `value` => Not a `float | int | str` type!"
        logger.critical(err_msg)
        raise PanicError(err_msg)
    if not isinstance(is_delete, bool):
        err_msg = "Class: `Unit` > Argument: `is_delete` => Not a `bool` type!"
        logger.critical(err_msg)
        raise PanicError(err_msg)

    self.field = field
    self.title = title
    self.value = value
    self.is_delete = is_delete

    self.check_empty_arguments()

check_empty_arguments()

Check the arguments (field|title|value) for empty values.

Returns:

Type Description
None

None

Source code in src/ramifice/unit.py
def check_empty_arguments(self) -> None:
    """Check the arguments (field|title|value) for empty values.

    Returns:
        `None`
    """
    field_name: str = ""

    if len(self.field) == 0:
        field_name = "field"
    elif len(self.title) == 0:
        field_name = "title"
    elif isinstance(self.value, str) and len(self.value) == 0:
        field_name = "value"

    if len(field_name) > 0:
        err_msg = (
            "Method: `unit_manager` > "
            + "Argument: `unit` > "
            + f"Field: `{field_name}` => "
            + "Must not be empty!"
        )
        logger.critical(err_msg)
        raise PanicError(err_msg)

from_dict(unit_dict) classmethod

Convert Unit-dictionary to a Unit instance.

Source code in src/ramifice/unit.py
@classmethod
def from_dict(cls: Any, unit_dict: dict[str, float | int | str | bool]) -> Any:
    """Convert Unit-dictionary to a Unit instance."""
    return cls(**unit_dict)

from_json(json_str) classmethod

Convert JSON-string to Unit instance.

Source code in src/ramifice/unit.py
@classmethod
def from_json(cls: Any, json_str: str) -> Any:
    """Convert JSON-string to Unit instance."""
    unit_dict = orjson.loads(json_str)
    return cls.from_dict(unit_dict)

to_dict()

Convert Unit instance to a dictionary.

Source code in src/ramifice/unit.py
def to_dict(self) -> dict[str, Any]:
    """Convert Unit instance to a dictionary."""
    unit_dict: dict[str, Any] = {}
    for key, value in self.__dict__.items():
        if not isinstance(value, Callable):
            unit_dict[key] = value
    return unit_dict

to_json()

Convert Unit instance to a JSON-string.

Source code in src/ramifice/unit.py
def to_json(self) -> str:
    """Convert Unit instance to a JSON-string."""
    return orjson.dumps(self.to_dict()).decode("utf-8")