Skip to content

serialization

cognite.powerops.utils.serialization.read_toml_file(toml_file)

Read a toml file and return a dictionary.

Parameters:

Name Type Description Default
toml_file Path | str

The path to the toml file.

required

Returns:

Type Description
dict[str, Any]

A dictionary with the toml data.

Source code in cognite/powerops/utils/serialization.py
def read_toml_file(toml_file: Path | str) -> dict[str, Any]:
    """
    Read a toml file and return a dictionary.

    Args:
        toml_file: The path to the toml file.

    Returns:
        A dictionary with the toml data.
    """
    return tomllib.loads(Path(toml_file).read_text())

cognite.powerops.utils.serialization.dump_toml_file(toml_file, data)

Dump a dictionary to a toml file.

Parameters:

Name Type Description Default
toml_file Path | str

The path to the toml file.

required
data dict[str, Any]

The data to dump.

required
Source code in cognite/powerops/utils/serialization.py
def dump_toml_file(toml_file: Path | str, data: dict[str, Any]) -> None:
    """
    Dump a dictionary to a toml file.

    Args:
        toml_file: The path to the toml file.
        data: The data to dump.

    """
    Path(toml_file).write_text(tomli_w.dumps(data))

cognite.powerops.utils.serialization.chdir(new_dir)

Change directory to new_dir and return to the original directory when exiting the context.

Parameters:

Name Type Description Default
new_dir Path

The new directory to change to.

required
Source code in cognite/powerops/utils/serialization.py
@contextlib.contextmanager
def chdir(new_dir: Path) -> Iterator[None]:
    """
    Change directory to new_dir and return to the original directory when exiting the context.

    Args:
        new_dir: The new directory to change to.

    """
    current_working_dir = Path.cwd()
    os.chdir(new_dir)

    try:
        yield

    finally:
        os.chdir(current_working_dir)

cognite.powerops.utils.serialization.load_yaml(yaml_path, expected_return_type='any', encoding='utf-8', clean_data=False)

load_yaml(yaml_path: Path, expected_return_type: Literal['dict'] = 'dict', encoding: str = 'utf-8', clean_data: bool = False) -> dict
load_yaml(yaml_path: Path, expected_return_type: Literal['list'], encoding: str = 'utf-8', clean_data: bool = False) -> list
load_yaml(yaml_path: Path, expected_return_type: Literal['any'], encoding: str = 'utf-8', clean_data: bool = False) -> list | dict

Fast loading of a yaml file.

Parameters:

Name Type Description Default
yaml_path Path

The path to the yaml file.

required
expected_return_type Literal['dict', 'list', 'any']

The expected return type. The function will raise an error if the file does not return the expected type. Defaults to any.

'any'
encoding str

The encoding of the yaml file. Defaults to utf-8.

'utf-8'
clean_data bool

Whether to clean the data from invalid characters. Defaults to False.

False

Returns:

Type Description
dict | list

The data in the yaml file as a dictionary.

Source code in cognite/powerops/utils/serialization.py
def load_yaml(
    yaml_path: Path,
    expected_return_type: Literal["dict", "list", "any"] = "any",
    encoding: str = "utf-8",
    clean_data: bool = False,
) -> dict | list:
    """
    Fast loading of a yaml file.

    Args:
        yaml_path: The path to the yaml file.
        expected_return_type: The expected return type. The function will raise an error
                              if the file does not return the expected type. Defaults to any.
        encoding: The encoding of the yaml file. Defaults to utf-8.
        clean_data: Whether to clean the data from invalid characters. Defaults to False.

    Returns:
        The data in the yaml file as a dictionary.
    """

    _validate(yaml_path)
    # The Windows Cpython implementation seems to guess if encoding is not explicitly set
    # This turns out to be a problem as it guesses wrong, which is not the case for Unix systems.
    data = Path(yaml_path).read_text(encoding=encoding)

    if clean_data and (invalid_characters := (set(data) - VALID_CHARACTERS)):
        data = re.sub(rf"[{'|'.join(invalid_characters)}]", UNRECOGNIZABLE_CHARACTER, data)
        warnings.warn(
            f"File {yaml_path.parent}/{yaml_path.name} contains invalid characters: {', '.join(invalid_characters)}",
            stacklevel=2,
        )
    output = CSafeLoader(data).get_data()
    if expected_return_type == "dict" and not isinstance(output, dict):
        if not output:
            warnings.warn(
                f"File {yaml_path.parent}/{yaml_path.name} contains no data",
                stacklevel=2,
            )
            return {}
        raise ValueError(f"Expected a dictionary, got {type(output)}")
    if expected_return_type == "list" and not isinstance(output, list):
        if not output:
            warnings.warn(
                f"File {yaml_path.parent}/{yaml_path.name} contains no data",
                stacklevel=2,
            )
            return []
        raise ValueError(f"Expected a list, got {type(output)}")
    return output

cognite.powerops.utils.serialization.dump_yaml(yaml_path, data, encoding='utf-8')

Dump a dictionary to a yaml file.

Parameters:

Name Type Description Default
yaml_path Path

The path to the yaml file.

required
data dict

The data to dump.

required
encoding str

The encoding of the yaml file. Defaults to utf-8.

'utf-8'
Source code in cognite/powerops/utils/serialization.py
def dump_yaml(yaml_path: Path, data: dict, encoding: str = "utf-8") -> None:
    """
    Dump a dictionary to a yaml file.

    Args:
        yaml_path: The path to the yaml file.
        data: The data to dump.
        encoding: The encoding of the yaml file. Defaults to utf-8.

    """
    _validate(yaml_path)
    with yaml_path.open("w", encoding=encoding) as stream:
        safe_dump(data, stream)