Skip to content

Commit 3fa5ece

Browse files
committed
Revert to ast parsing
1 parent 0a98c4f commit 3fa5ece

File tree

2 files changed

+33
-19
lines changed

2 files changed

+33
-19
lines changed

daskms/tests/test_utils.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,12 @@
1919
def test_parse_chunks_dict():
2020
assert parse_chunks_dict("{row: 1000}") == {"row": 1000}
2121
assert parse_chunks_dict("{row: 1000, chan: 64}") == {"row": 1000, "chan": 64}
22+
assert parse_chunks_dict("{row: (10, 10), chan: (4, 4)}") == {
23+
"row": (10, 10),
24+
"chan": (4, 4),
25+
}
2226

23-
with pytest.raises(ValueError):
27+
with pytest.raises(SyntaxError):
2428
parse_chunks_dict("row:1000}")
2529

2630

daskms/utils.py

+28-18
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# -*- coding: utf-8 -*-
22

3+
import ast
34
from collections import OrderedDict
45
import logging
56
from pathlib import PurePath, Path
@@ -17,26 +18,35 @@
1718
log = logging.getLogger(__name__)
1819

1920

20-
def parse_chunks_dict(chunks_str):
21-
chunks_str = chunks_str.strip()
22-
e = ValueError(
23-
f"{chunks_str} is not of the form {{dim_1: size_1, ..., dim_n, size_n}}"
24-
)
25-
if not (chunks_str.startswith("{") and chunks_str.endswith("}")):
26-
raise e
21+
class ChunkTransformer(ast.NodeTransformer):
22+
def visit_Module(self, node):
23+
if len(node.body) != 1 or not isinstance(node.body[0], ast.Expr):
24+
raise ValueError("Module must contain a single expression")
2725

28-
chunks = {}
26+
expr = node.body[0]
2927

30-
for kvmap in chunks_str[1:-1].split(","):
31-
try:
32-
k, v = (p.strip() for p in kvmap.split(":"))
33-
v = int(v)
34-
except (IndexError, ValueError):
35-
raise e
36-
else:
37-
chunks[k] = v
38-
39-
return chunks
28+
if not isinstance(expr.value, ast.Dict):
29+
raise ValueError("Expression must contain a dictionary")
30+
31+
return self.visit(expr).value
32+
33+
def visit_Dict(self, node):
34+
keys = [self.visit(k) for k in node.keys]
35+
values = [self.visit(v) for v in node.values]
36+
return {k: v for k, v in zip(keys, values)}
37+
38+
def visit_Name(self, node):
39+
return node.id
40+
41+
def visit_Tuple(self, node):
42+
return tuple(self.visit(v) for v in node.elts)
43+
44+
def visit_Constant(self, node):
45+
return node.n
46+
47+
48+
def parse_chunks_dict(chunks_str):
49+
return ChunkTransformer().visit(ast.parse(chunks_str))
4050

4151

4252
def natural_order(key):

0 commit comments

Comments
 (0)