openPMD/openPMD-api

Attribute Getting: Default Param

Open

#477 opened on Feb 17, 2019

 (2 comments) (0 reactions) (0 assignees)C++ (57 forks)auto 404
frontend: C++17good first issuehelp wanted

Repository metrics

Stars
 (160 stars)
PR merge metrics
 (PR metrics pending)

Description

While reading attributes, it would be useful for many cases to return an "empty default" instead of throwing an openPMD::no_such_attribute_error on missing.

Therefore, we should introduce an additional, optional parameter in e.g. Series.author() and Attribute.get() that if set, is returned in case of exceptions (instead of an exception).

This is similar to Python's dict() handling: Python:

dict = {'A': 'One', 'B': 2}

d = {'A': 'One', 'B': 2}

d.get('A')
# 'One'
d.get('B')
# 2

d.get('C')
#
d.get('C') == None
# True
# d.get('C', 'fallback')
# 'fallback'

or C++

// ...

auto s = openPMD::Series(/* ... */);

s.author();
// might throw

s.author("");
// new variant 1: return empty string if attribute is missing

// variant 2: let openPMD-class "attribute getters"
// return by default the empty variant of itself as a
// fallback:
s.author();
// "" or attribute value


// now to "Attributable"

s.getAttribute("key");
// might throw

s.getAttribute("key", "");
// new variant 1: fallback to empty string

s.getAttribute("key");
// new variant 2: return empty string if attribute is missing

// note: actually in `Attribute::get()`
// but that might be too late

Current handling with containsAttribute(key) or try-catch are a bit too verbose.

We could also consider returning an std::optional. C++11 implementations:

Or using std::monostate with our variant:

Contributor guide