Skip to content

Commit 59835f9

Browse files
committed
[tools/dictparser] Add parse_cardinality method
1 parent efaa298 commit 59835f9

1 file changed

Lines changed: 46 additions & 1 deletion

File tree

odml/tools/dict_parser.py

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,47 @@
88
from .parser_utils import InvalidVersionException, ParserException, odml_tuple_export
99

1010

11+
def parse_cardinality(vals):
12+
"""
13+
Parses an odml specific cardinality from an input value.
14+
15+
If the input content is valid, returns an appropriate tuple.
16+
Returns None if the input is empty or the content cannot be
17+
properly parsed.
18+
19+
:param vals: list or tuple
20+
:return: None or 2-tuple
21+
"""
22+
if not vals:
23+
return None
24+
25+
if isinstance(vals, (list, tuple)) and len(vals) == 2:
26+
min_val = vals[0]
27+
max_val = vals[1]
28+
29+
if min_val is None or str(min_val).strip() == "None":
30+
min_val = None
31+
32+
if max_val is None or str(max_val).strip() == "None":
33+
max_val = None
34+
35+
min_int = isinstance(min_val, int) and min_val >= 0
36+
max_int = isinstance(max_val, int) and max_val >= 0
37+
38+
if min_int and max_int and max_val > min_val:
39+
return min_val, max_val
40+
41+
if min_int and not max_val:
42+
return min_val, None
43+
44+
if max_int and not min_val:
45+
return None, max_val
46+
47+
# We were not able to properly parse the current cardinality, so add
48+
# an appropriate Error/Warning once the reader 'ignore_errors' option has been implemented.
49+
return None
50+
51+
1152
class DictWriter:
1253
"""
1354
A writer to parse an odml.Document to a Python dictionary object equivalent.
@@ -255,8 +296,12 @@ def parse_properties(self, props_list):
255296
for i in _property:
256297
attr = self.is_valid_attribute(i, odmlfmt.Property)
257298
if attr:
299+
content = _property[attr]
300+
if attr.endswith("_cardinality"):
301+
content = parse_cardinality(content)
302+
258303
# Make sure to always use the correct odml format attribute name
259-
prop_attrs[odmlfmt.Property.map(attr)] = _property[attr]
304+
prop_attrs[odmlfmt.Property.map(attr)] = content
260305

261306
prop = odmlfmt.Property.create(**prop_attrs)
262307
odml_props.append(prop)

0 commit comments

Comments
 (0)