def test_restore_flattened_dict_with_box_class():
    nested_dict = Box(a=Box(x=1), b=Box(y=2))
    flat = collections.dict_to_flatdict(nested_dict)
    restored = collections.flatdict_to_dict(flat)
    assert isinstance(restored, dict)

    restored_Box = collections.flatdict_to_dict(flat, dct_class=Box)
    assert isinstance(restored_Box, Box)
    assert isinstance(restored_Box.a, Box)
    assert restored_Box.a == nested_dict.a
def test_flatten_dict(nested_dict):
    flat = collections.dict_to_flatdict(nested_dict)
    assert flat == {
        collections.CompoundKey([1]): 2,
        collections.CompoundKey([2, 1]): 2,
        collections.CompoundKey([2, 3]): 4,
        collections.CompoundKey([3, 1]): 2,
        collections.CompoundKey([3, 3, 4]): 5,
        collections.CompoundKey([3, 3, 6, 7]): 8,
    }
Beispiel #3
0
def interpolate_config(
    config: dict, env_var_prefix: Optional[str] = None
) -> collections.Config:
    """
    Processes the initial input configuration and replaces
    system variables ($PROJECT_PATH, etc.) as well as our
    custom variables ("${}" syntax).

    Args:
        - config (dict): Loaded data from a configuration file
        - env_var_prefix (Optional[str]): Environment variable prefix to
            load from the current environment.

    Returns:
        - collections.Config: Configuration object with values populated
            and accessible via dot notation or dictionary notation.
    """

    # Toml & other file formats support nested
    # dictionaries, so we need to flatten them out
    # to avoid recursive checking when interpolating
    flat_config = collections.dict_to_flatdict(config)

    if env_var_prefix is not None:
        env_vars = load_environment_variables(env_var_prefix)
        flat_config = {**flat_config, **env_vars}

    # Interpolate any environment variables referenced
    for key, value in list(flat_config.items()):
        value = interpolate_env_vars(value)
        if isinstance(value, str):
            value = string_to_type(value)

        flat_config[key] = value

    flat_config = replace_variable_references(flat_config)
    return cast(
        collections.Config,
        collections.flatdict_to_dict(flat_config, dct_class=collections.Config),
    )
def test_restore_flattened_dict(nested_dict):
    flat = collections.dict_to_flatdict(nested_dict)
    restored = collections.flatdict_to_dict(flat)
    assert restored == nested_dict