generated from mpi-astronomy/mpia-python-template
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
override Dataset __setattr__ function
With this commit, it is possible to do Dataset.name = value instead of the usual Dataset['name'] = (coords, value). There may be a good reason that this is currently blocked by xarray, but none immediately came to mind so I thought this would be worth trying. Another alternative to this is to do Dataset.name.data = value if your 'name' DataArray was called 'data'. This is already possible with the default xarray Dataset object.
- Loading branch information
1 parent
c04defe
commit 55654db
Showing
3 changed files
with
29 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -129,3 +129,6 @@ dmypy.json | |
|
||
# Pyre type checker | ||
.pyre/ | ||
|
||
# VS Code workspaces | ||
*.code-workspace |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
from typing import Any | ||
import xarray as xr | ||
|
||
|
||
class Dataset(xr.Dataset): | ||
# Need to define this to avoid warning messages | ||
__slots__ = ("_dataset",) | ||
|
||
def __setattr__(self, name: str, value: Any) -> None: | ||
"""Overwrite the setattr function to allow behaviour like Dataset.name = value instead of the usual Dataset['name'] = (coords, value). | ||
""" | ||
try: | ||
object.__setattr__(self, name, value) | ||
except AttributeError as e: | ||
try: | ||
if str(e) != "{!r} object has no attribute {!r}".format( | ||
type(self).__name__, name | ||
): | ||
raise e | ||
else: | ||
self[name] = (list(self.coords), value) | ||
except Exception as e2: | ||
raise e2 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters