def _parse_typed_value()

in lm_human_preferences/utils/hyperparams.py [0:0]


def _parse_typed_value(ty, s):
    if ty is str:
        return s
    elif ty in (int, float):
        return ty(s)
    elif ty is bool:
        if s in ('t', 'true', 'True'):
            return True
        elif s in ('f', 'false', 'False'):
            return False
        else:
            raise ValueError(f"Invalid bool '{s}'")
    elif ty is type(None):
        if s in ('None', 'none', ''):
            return None
        else:
            raise ValueError(f"Invalid None value '{s}'")
    elif is_hparam_type(ty):
        if s in ('on', 'off'):
            # The class will be constructed later
            return s
        else:
            raise ValueError(f"Invalid hparam class value '{s}'")
    elif _is_union_type(ty):
        if not _can_distinguish_unambiguously(ty.__args__):
            raise TypeError(f"Can't always unambiguously parse a value of union '{ty}'")
        for ty_option in ty.__args__:
            try:
                return _parse_typed_value(ty_option, s)
            except ValueError:
                continue
        raise ValueError(f"Couldn't parse '{s}' as any of the types in '{ty}'")
    else:
        raise ValueError(f"Unsupported hparam type '{ty}'")