Skip to content

Commit

Permalink
Allow weakref (#3318)
Browse files Browse the repository at this point in the history
* Allow weakref

* black

* What's New tweak

* Update doc/whats-new.rst

Co-Authored-By: Maximilian Roos <5635139+max-sixty@users.noreply.github.com>
  • Loading branch information
crusaderky and max-sixty authored Sep 18, 2019
1 parent fedc95f commit fddced0
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 1 deletion.
8 changes: 8 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ What's New
v0.13.1 (unreleased)
--------------------

Bug fixes
~~~~~~~~~
- Reintroduce support for :mod:`weakref` (broken in v0.13.0). Support has been
reinstated for :class:`DataArray` and :class:`Dataset` objects only. Internal xarray
objects remain unaddressable by weakref in order to save memory.
(:issue:`3317`) by `Guido Imperiale <https://github.com/crusaderky>`_.


.. _whats-new.0.13.0:

v0.13.0 (17 Sep 2019)
Expand Down
10 changes: 9 additions & 1 deletion xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,15 @@ class DataArray(AbstractArray, DataWithCoords):
Dictionary for holding arbitrary metadata.
"""

__slots__ = ("_accessors", "_coords", "_file_obj", "_name", "_indexes", "_variable")
__slots__ = (
"_accessors",
"_coords",
"_file_obj",
"_name",
"_indexes",
"_variable",
"__weakref__",
)

_groupby_cls = groupby.DataArrayGroupBy
_rolling_cls = rolling.DataArrayRolling
Expand Down
1 change: 1 addition & 0 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,7 @@ class Dataset(Mapping, ImplementsDatasetReduce, DataWithCoords):
"_file_obj",
"_indexes",
"_variables",
"__weakref__",
)

_groupby_cls = groupby.DatasetGroupBy
Expand Down
11 changes: 11 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -4672,3 +4672,14 @@ class MyArray(DataArray):
pass

assert str(e.value) == "MyArray must explicitly define __slots__"


def test_weakref():
"""Classes with __slots__ are incompatible with the weakref module unless they
explicitly state __weakref__ among their slots
"""
from weakref import ref

a = DataArray(1)
r = ref(a)
assert r() is a
11 changes: 11 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -5786,3 +5786,14 @@ class MyDS(Dataset):
pass

assert str(e.value) == "MyDS must explicitly define __slots__"


def test_weakref():
"""Classes with __slots__ are incompatible with the weakref module unless they
explicitly state __weakref__ among their slots
"""
from weakref import ref

ds = Dataset()
r = ref(ds)
assert r() is ds

0 comments on commit fddced0

Please sign in to comment.