From e7305c6fcdc51d04196d31e0417f527eeb4a71ac Mon Sep 17 00:00:00 2001 From: Tamas Gal <tgal@km3net.de> Date: Mon, 1 Feb 2021 18:51:36 +0100 Subject: [PATCH] Fallback to dictionary/tuple for invalid attributes --- km3io/offline.py | 21 +++++++++++++++------ tests/test_offline.py | 14 ++++++++++++++ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/km3io/offline.py b/km3io/offline.py index c593024..b93802b 100644 --- a/km3io/offline.py +++ b/km3io/offline.py @@ -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] diff --git a/tests/test_offline.py b/tests/test_offline.py index c9fd88f..63f6c8e 100644 --- a/tests/test_offline.py +++ b/tests/test_offline.py @@ -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 -- GitLab