Skip to content

deffcode.utils

Following are the helper methods required by the DeFFcode APIs.

For usage examples, kindly refer our Basic Recipes 🍰 and Advanced Recipes 🥐

 

logger_handler

Returns the logger handler

Returns: A logger handler

Source code in deffcode/utils.py
def logger_handler() -> logging.Handler:
    """
    ## logger_handler

    Returns the logger handler

    **Returns:** A logger handler
    """
    # logging formatter
    formatter = ColoredFormatter(
        "{green}{asctime}{reset} :: {bold_purple}{name:^13}{reset} :: {log_color}{levelname:^8}{reset} :: {bold_white}{message}",
        datefmt="%H:%M:%S",
        reset=True,
        log_colors={
            "INFO": "bold_cyan",
            "DEBUG": "bold_yellow",
            "WARNING": "bold_red,fg_thin_yellow",
            "ERROR": "bold_red",
            "CRITICAL": "bold_red,bg_white",
        },
        style="{",
    )
    # check if FFdecoder_LOGFILE defined
    file_mode = os.environ.get("DEFFCODE_LOGFILE", False)
    # define handler
    handler = logging.StreamHandler()
    if file_mode and isinstance(file_mode, str):
        file_path = os.path.abspath(file_mode)
        if (os.name == "nt" or os.access in os.supports_effective_ids) and os.access(
            os.path.dirname(file_path), os.W_OK
        ):
            file_path = (
                os.path.join(file_path, "deffcode.log") if os.path.isdir(file_path) else file_path
            )
            handler = logging.FileHandler(file_path, mode="a")
            formatter = logging.Formatter(
                "{asctime} :: {name} :: {levelname} :: {message}",
                datefmt="%H:%M:%S",
                style="{",
            )

    handler.setFormatter(formatter)
    return handler

 

dict2Args

Converts dictionary attributes to list(args)

Parameters:

Name Type Description Default
param_dict dict

Parameters dictionary

required

Returns: Arguments list

Source code in deffcode/utils.py
def dict2Args(param_dict: dict[str, Any]) -> list[str]:
    """
    ## dict2Args

    Converts dictionary attributes to list(args)

    Parameters:
        param_dict (dict): Parameters dictionary

    **Returns:** Arguments list
    """
    args: list[str] = []
    for key in param_dict:
        if key in ["-clones"] or key.startswith("-core"):
            if isinstance(param_dict[key], list):
                args.extend(param_dict[key])
            else:
                logger.warning(
                    "{} with invalid datatype:`{}`, Skipped!".format(
                        "Core parameter" if key.startswith("-core") else "Clone",
                        param_dict[key],
                    )
                )
        else:
            args.append(key)
            args.append(str(param_dict[key]))
    return args

 

delete_ext_safe

Safely deletes files at given path.

Parameters:

Name Type Description Default
file_path string

path to the file

required
Source code in deffcode/utils.py
def delete_file_safe(file_path: str | os.PathLike[str]) -> None:
    """
    ## delete_ext_safe

    Safely deletes files at given path.

    Parameters:
        file_path (string): path to the file
    """
    try:
        dfile = Path(file_path)
        dfile.unlink(missing_ok=True)
    except Exception as e:
        logger.exception(str(e))

 

validate_device_index

Validates if given device index is valid or not? Only Integers or String of integers are valid indexes.

Parameters:

Name Type Description Default
index int / str

Index of the device

required

Returns: A boolean value, confirming whether valid, or not?.

Source code in deffcode/utils.py
def validate_device_index(index: int | str | Any) -> bool:
    """
    ## validate_device_index

    Validates if given device index is valid or not? Only Integers or String of integers are valid indexes.

    Parameters:
        index (int/str): Index of the device

    **Returns:** A boolean value, confirming whether valid, or not?.
    """
    # validate index value
    if isinstance(index, int):
        # return true
        return True
    elif isinstance(index, str):
        # remove any whitespaces
        index.replace(" ", "")
        # return true
        return bool(index.isnumeric() or (index.startswith("-") and index[1:].isnumeric()))
    else:
        # return false otherwise
        return False