openPMD / openPMD/openPMD-api

Attribute Getting: Default Param

Open
#477 2 comments 0 reactions 0 assignees View on GitHub
frontend: C++17 good first issue help wanted
Dominant language
C++
Stars
161
Forks
59
Avg merge
2d 22h
Merged PRs (30d)
7

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:
```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++
```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:
- https://github.com/martinmoene/optional-lite
- https://github.com/TartanLlama/optional (probably best suited)

Or using `std::monostate` with our variant:
- https://en.cppreference.com/w/cpp/utility/variant/monostate
- included in `MPark.Variant` as `mpark::monostate`

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.