# Copyright 2025–2026 European Union
# Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
# SPDX-License-Identifier: EUPL-1.2
"""
Typing helper service module for radioviz application.
This module provides utility functions for handling optional variables in a
statically typed environment. It offers options for runtime checks and static
analysis assumptions to simplify code that deals with variables guaranteed
to be initialized at runtime but defined as Optional[T] for various reasons.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Optional, TypeVar
T = TypeVar('T')
"""
Generic type variable for typing helpers.
"""
[docs]
def require_not_none(value: Optional[T], name: str = 'Variable') -> T:
"""
Ensure that a value is not None at runtime and return it with non-Optional type.
:param value: The value to check for being not None.
:type value: Optional[T]
:param name: The name of the variable to use in the error message if it's None.
:type name: str
:return: The value as type T, guaranteed to be not None.
:rtype: T
:raise RuntimeError: If the value is None.
"""
if value is None:
raise RuntimeError(f'{name} is not initialized.')
return value
[docs]
def assume_not_none(value: Optional[T]) -> T:
"""
Assume that a value is not None for static typing purposes and return it with non-Optional type.
This function performs an assertion within a TYPE_CHECKING block to satisfy the
static type checker without introducing runtime overhead. Use this function when
you are certain the value is initialized but want to avoid runtime checks.
:param value: The value to assume is not None.
:type value: Optional[T]
:return: The value as type T, assumed to be not None.
:rtype: T
"""
if TYPE_CHECKING:
assert value is not None
return value