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 committed Aug 5, 2024
1 parent 6baf91e commit 0139331
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
18 changes: 18 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,20 @@ def to_absolute_path(path: str) -> str:
else:
ret = base / p
return str(ret)


def to_hydra_override_value_str(obj: Any) -> str:
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)
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 0139331

Please sign in to comment.