Skip to content

ureg

Functions:

Name Description
check_unit

Functions#

check_unit #

check_unit(unit_str: str, keep_exp: bool) -> str
Source code in tsdat/config/variables/ureg.py
def check_unit(unit_str: str, keep_exp: bool) -> str:
    unit_str = unit_str.strip()

    if not unit_str or unit_str == "1":
        return unit_str

    # Not recognized by pint, but we want it to be valid
    if unit_str.lower().startswith("seconds since"):
        return unit_str

    # Add exponent symbol (m2 s-2 -> m^2 s^-2)
    carrot_flag = 1 if "^" in unit_str else 0
    unit_exponent = re.compile(
        r"(?<=[A-Za-z\)])(?![A-Za-z\)])" r"(?<![0-9\-][eE])(?<![0-9\-])(?=[0-9\-])"
    )
    unit_str = unit_exponent.sub("^", unit_str)

    # Validate with pint unit registry
    ureg(unit_str)

    # Remove exponent if not used
    if not keep_exp and not carrot_flag:
        unit_str = unit_str.replace("^", "")

    if not unit_str:
        return "1"

    return unit_str