Skip to content

Commit

Permalink
Add a util function to convert basic python objects to override format (
Browse files Browse the repository at this point in the history
  • Loading branch information
jesszzzz authored Aug 7, 2024
1 parent 9deaa6c commit 6557a93
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
28 changes: 28 additions & 0 deletions hydra/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved

import json
import logging.config
import os
from pathlib import Path
Expand Down Expand Up @@ -115,3 +116,30 @@ def to_absolute_path(path: str) -> str:
else:
ret = base / p
return str(ret)


def to_hydra_override_value_str(obj: Any) -> str:
"""
Basic conversion of an object to a string that can be used in a Hydra override.
Does not explicitly support all types but should work for basic structures.
>>> obj = {"foo": 1, "bar": "baz"}
>>> compose(config_name="config", overrides=[f"a={to_hydra_override_value_str(obj)}", "x=1"])
:param obj: object to convert
:return: string representation of the object that can be used in a Hydra override
"""
if isinstance(obj, dict):
return (
"{"
+ ", ".join(
f"{key}: {to_hydra_override_value_str(value)}"
for key, value in obj.items()
)
+ "}"
)
elif isinstance(obj, list):
return (
"[" + ", ".join([to_hydra_override_value_str(value) for value in obj]) + "]"
)
return json.dumps(obj)
1 change: 1 addition & 0 deletions news/2934.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add to_hydra_override_value_str util function
19 changes: 19 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,25 @@ def test_to_absolute_path_without_hydra(
assert utils.to_absolute_path(path) == expected


@mark.parametrize(
"obj, expected",
[
("foo bar", '"foo bar"'),
(10, "10"),
({"foo": '\\"bar'}, '{foo: "\\\\\\"bar"}'),
([1, 2, "3", {"a": "xyz"}], '[1, 2, "3", {a: "xyz"}]'),
(
{"a": 10, "b": "c", "d": {"e": [1, 2, "3"], "f": ["g", {"h": {"i": "j"}}]}},
'{a: 10, b: "c", d: {e: [1, 2, "3"], f: ["g", {h: {i: "j"}}]}}',
),
],
)
def test_to_hydra_override_value_str(
hydra_restore_singletons: Any, obj: Any, expected: str
) -> None:
assert utils.to_hydra_override_value_str(obj) == expected


@mark.parametrize(
"env_setting,expected_error",
[
Expand Down

0 comments on commit 6557a93

Please sign in to comment.