Skip to content

Commit fddced0

Browse files
Allow weakref (#3318)
* Allow weakref * black * What's New tweak * Update doc/whats-new.rst Co-Authored-By: Maximilian Roos <[email protected]>
1 parent fedc95f commit fddced0

File tree

5 files changed

+40
-1
lines changed

5 files changed

+40
-1
lines changed

doc/whats-new.rst

+8
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,14 @@ What's New
1818
v0.13.1 (unreleased)
1919
--------------------
2020

21+
Bug fixes
22+
~~~~~~~~~
23+
- Reintroduce support for :mod:`weakref` (broken in v0.13.0). Support has been
24+
reinstated for :class:`DataArray` and :class:`Dataset` objects only. Internal xarray
25+
objects remain unaddressable by weakref in order to save memory.
26+
(:issue:`3317`) by `Guido Imperiale <https://github.com/crusaderky>`_.
27+
28+
2129
.. _whats-new.0.13.0:
2230

2331
v0.13.0 (17 Sep 2019)

xarray/core/dataarray.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,15 @@ class DataArray(AbstractArray, DataWithCoords):
248248
Dictionary for holding arbitrary metadata.
249249
"""
250250

251-
__slots__ = ("_accessors", "_coords", "_file_obj", "_name", "_indexes", "_variable")
251+
__slots__ = (
252+
"_accessors",
253+
"_coords",
254+
"_file_obj",
255+
"_name",
256+
"_indexes",
257+
"_variable",
258+
"__weakref__",
259+
)
252260

253261
_groupby_cls = groupby.DataArrayGroupBy
254262
_rolling_cls = rolling.DataArrayRolling

xarray/core/dataset.py

+1
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,7 @@ class Dataset(Mapping, ImplementsDatasetReduce, DataWithCoords):
420420
"_file_obj",
421421
"_indexes",
422422
"_variables",
423+
"__weakref__",
423424
)
424425

425426
_groupby_cls = groupby.DatasetGroupBy

xarray/tests/test_dataarray.py

+11
Original file line numberDiff line numberDiff line change
@@ -4672,3 +4672,14 @@ class MyArray(DataArray):
46724672
pass
46734673

46744674
assert str(e.value) == "MyArray must explicitly define __slots__"
4675+
4676+
4677+
def test_weakref():
4678+
"""Classes with __slots__ are incompatible with the weakref module unless they
4679+
explicitly state __weakref__ among their slots
4680+
"""
4681+
from weakref import ref
4682+
4683+
a = DataArray(1)
4684+
r = ref(a)
4685+
assert r() is a

xarray/tests/test_dataset.py

+11
Original file line numberDiff line numberDiff line change
@@ -5786,3 +5786,14 @@ class MyDS(Dataset):
57865786
pass
57875787

57885788
assert str(e.value) == "MyDS must explicitly define __slots__"
5789+
5790+
5791+
def test_weakref():
5792+
"""Classes with __slots__ are incompatible with the weakref module unless they
5793+
explicitly state __weakref__ among their slots
5794+
"""
5795+
from weakref import ref
5796+
5797+
ds = Dataset()
5798+
r = ref(ds)
5799+
assert r() is ds

0 commit comments

Comments
 (0)