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.
Merge pull request #1 from taylorbell57/setattr
override Dataset __setattr__ function
- Loading branch information
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