Skip to content

Commit 05ddf23

Browse files
authored
Adjust CLI dict arg parsing to handle empty string value
Differential Revision: D57515667 Pull Request resolved: #914
1 parent fffd1e2 commit 05ddf23

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

torchx/util/test/types_test.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,10 @@ def test_to_dict(self) -> None:
150150
self.assertDictEqual({"FOO": "v1,v2"}, to_dict("FOO=v1,v2"))
151151
self.assertDictEqual({"FOO": "v1;v2"}, to_dict("FOO=v1;v2"))
152152

153+
# Handles empty strings as a special case
154+
self.assertDictEqual({"FOO": ""}, to_dict("FOO=''"))
155+
self.assertDictEqual({"FOO": ""}, to_dict('FOO=""'))
156+
153157
# trailing delimiters preserved
154158
# a delim without the next key should be interpreted as the value for FOO
155159
self.assertDictEqual({"FOO": ","}, to_dict("FOO=,"))

torchx/util/types.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ def to_dict(arg: str) -> Dict[str, str]:
4545
4646
to_dict("FOO=v1") == {"FOO": "v1"}
4747
48+
to_dict("FOO=''") == {"FOO": ""}
49+
to_dict('FOO=""') == {"FOO": ""}
50+
4851
to_dict("FOO=v1,v2") == {"FOO": "v1,v2"]}
4952
to_dict("FOO=v1;v2") == {"FOO": "v1;v2"]}
5053
to_dict("FOO=v1;v2") == {"FOO": "v1;v2,"]}
@@ -70,6 +73,9 @@ def parse_val_key(vk: str) -> Tuple[str, str]:
7073
else:
7174
return vk[0:idx].strip(), vk[idx + 1 :].strip()
7275

76+
def to_val(val: str) -> str:
77+
return val if val != '""' and val != "''" else ""
78+
7379
arg_map: Dict[str, str] = {}
7480

7581
if not arg:
@@ -92,10 +98,10 @@ def parse_val_key(vk: str) -> Tuple[str, str]:
9298
# middle elements are value_{n}<delim>key_{n+1}
9399
for vk in split_arg[1 : split_arg_len - 1]: # python deals with
94100
val, key_next = parse_val_key(vk)
95-
arg_map[key] = val
101+
arg_map[key] = to_val(val)
96102
key = key_next
97103
val = split_arg[-1] # last element is always a value
98-
arg_map[key] = val
104+
arg_map[key] = to_val(val)
99105
return arg_map
100106

101107

0 commit comments

Comments
 (0)