Skip to content

Commit f4b7202

Browse files
committed
[odml/property] Fix py2 odml tuple issue
When loading odml style tuples from a yaml or json file with Python 2, the string containing the tuples is not properly parsed from a unicode string to a list of odml style tuples. With JSON and YAML in Python 3 this conversion works out of the box but to not break Python 2 compatibility already this hotfix is introduced.
1 parent 8fe2d43 commit f4b7202

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

odml/property.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,38 @@
1010
from .tools.doc_inherit import inherit_docstring, allow_inherit_docstring
1111

1212

13+
def odml_tuple_import(t_count, new_value):
14+
"""
15+
Checks via a heuristic if the values in a string fit the general
16+
odml style tuple format and the individual items match the
17+
required number of tuple values.
18+
Legacy Python2 code required to parse unicode strings to a list
19+
of odml style tuples.
20+
21+
:param t_count: integer, required values within a single odml style tuple.
22+
:param new_value: string containing an odml style tuple list.
23+
:return: list of odml style tuples.
24+
"""
25+
try:
26+
unicode = unicode
27+
except NameError:
28+
unicode = str
29+
30+
if len(new_value) != 1 and not isinstance(new_value[0], unicode):
31+
return new_value
32+
33+
cln = new_value[0].strip()
34+
l_check = cln.startswith("[") and cln.endswith("]")
35+
br_check = cln.count("(") == cln.count(")")
36+
com_check = cln.count("(") == (cln.count(",") + 1)
37+
sep_check = t_count == 1 or cln.count("(") == (cln.count(";") / (t_count - 1))
38+
39+
if l_check and br_check and com_check and sep_check:
40+
new_value = cln[1:-1].split(",")
41+
42+
return new_value
43+
44+
1345
@allow_inherit_docstring
1446
class BaseProperty(base.BaseObject):
1547
"""
@@ -346,6 +378,12 @@ def values(self, new_value):
346378
if self._dtype is None:
347379
self._dtype = dtypes.infer_dtype(new_value[0])
348380

381+
# Python2 legacy code for loading odml style tuples from YAML or JSON.
382+
# Works from Python 3 onwards.
383+
if self._dtype.endswith("-tuple") and not self._validate_values(new_value):
384+
t_count = int(self._dtype.split("-")[0])
385+
new_value = odml_tuple_import(t_count, new_value)
386+
349387
if not self._validate_values(new_value):
350388
if self._dtype in ("date", "time", "datetime"):
351389
req_format = dtypes.default_values(self._dtype)

0 commit comments

Comments
 (0)