Source code for bragi_quantum.datalayer.utils.nested

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   QC2 @ CHALMERS CALIBRATION TOOLKIT
#   (c) 2026 Chalmers University of Technology and Project Contributors
# ──────────────────────────────────────────────────────────────────────────
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       https://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
# ──────────────────────────────────────────────────────────────────────────
#   CONTRIBUTORS list:
#
#   Matteo Robbiati, robbiati@chalmers.se
#   Emil Hogedal, emil.hogedal@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


import json
import logging
from typing import Any

logger = logging.getLogger(__name__)


[docs] def get_nested_value(obj: Any, path: str) -> Any: """Recursively navigate a dotted path and return the value at its end. Counterpart to :func:`set_nested_value`; used to snapshot a value before overriding it (e.g. by the ``bragi_quantum.datalayer.utils.context`` managers). Unlike ``set_nested_value`` this does not swallow missing attributes — a bad path raises ``AttributeError`` so typos fail fast rather than silently no-op. """ for part in path.split("."): obj = getattr(obj, part) return obj
[docs] def set_nested_value(obj: Any, path: str, value: Any): """ Recursively navigates a dotted path and sets the value. Includes automatic float conversion for YAML scientific notation, and automatic JSON decoding for values Redis can only store as a string (e.g. a list-valued QOI field JSON-encoded before being hset — see ``bragi_quantum.datalayer.managing.redis._redis_safe_value``), so ``load_calibration_state`` hands the live device back a real list/dict instead of that raw string. """ if isinstance(value, str): try: value = float(value) except ValueError: try: value = json.loads(value) except (json.JSONDecodeError, TypeError): pass parts = path.split(".") try: for part in parts[:-1]: obj = getattr(obj, part) target = getattr(obj, parts[-1]) if callable(target) and hasattr(target, "set"): target(value) else: setattr(obj, parts[-1], value) except AttributeError: logger.debug(f"Path '{path}' not found on {obj.name}. Skipping.")