Skip to content
Snippets Groups Projects
Commit e7305c6f authored by Tamas Gal's avatar Tamas Gal :speech_balloon:
Browse files

Fallback to dictionary/tuple for invalid attributes

parent db635a2f
No related branches found
No related tags found
1 merge request!50Fallback to dictionary/tuple for invalid attributes
Pipeline #17438 passed
......@@ -113,17 +113,23 @@ class Header:
values += [None] * (n_max - n_values)
fields += ["field_{}".format(i) for i in range(n_fields, n_max)]
Constructor = namedtuple(attribute, fields)
if not values:
continue
self._data[attribute] = Constructor(
**{f: to_num(v) for (f, v) in zip(fields, values)}
)
entry = {f: to_num(v) for (f, v) in zip(fields, values)}
try:
self._data[attribute] = namedtuple(attribute, fields)(**entry)
except ValueError:
self._data[attribute] = [to_num(v) for v in values]
for attribute, value in self._data.items():
setattr(self, attribute, value)
try:
setattr(self, attribute, value)
except ValueError:
log.warning(
f"Invalid attribute name for header entry '{attribute}'"
", access only as dictionary key."
)
def __str__(self):
lines = ["MC Header:"]
......@@ -134,3 +140,6 @@ class Header:
else:
lines.append(" {}: {}".format(key, value))
return "\n".join(lines)
def __getitem__(self, key):
return self._data[key]
......@@ -98,6 +98,20 @@ class TestHeader(unittest.TestCase):
assert "test" == header.undefined.field_2
assert 3.4 == header.undefined.field_3
def test_header_with_invalid_field_or_attribute_names(self):
head = {
"a": "1 2 3",
"b+c": "4 5 6",
}
header = Header(head)
assert 1 == header["a"][0]
assert 2 == header["a"][1]
assert 3 == header["a"][2]
assert 4 == header["b+c"][0]
assert 5 == header["b+c"][1]
assert 6 == header["b+c"][2]
def test_reading_header_from_sample_file(self):
head = OFFLINE_NUMUCC.header
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment