|
1 | 1 | # -*- coding: utf-8 -*-
|
2 | 2 |
|
| 3 | +import ast |
3 | 4 | from collections import OrderedDict
|
4 | 5 | import logging
|
5 | 6 | from pathlib import PurePath, Path
|
|
17 | 18 | log = logging.getLogger(__name__)
|
18 | 19 |
|
19 | 20 |
|
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") |
27 | 25 |
|
28 |
| - chunks = {} |
| 26 | + expr = node.body[0] |
29 | 27 |
|
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)) |
40 | 50 |
|
41 | 51 |
|
42 | 52 | def natural_order(key):
|
|
0 commit comments