Skip to content

Commit

Permalink
Dimension objects should stay singletons even when pickled
Browse files Browse the repository at this point in the history
  • Loading branch information
mstimberg committed Nov 4, 2022
1 parent 427cc7c commit bc94a69
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
12 changes: 12 additions & 0 deletions brian2/tests/test_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,18 @@ def test_pickling():
assert_equal(unpickled, q)


@pytest.mark.codegen_independent
def test_dimension_singletons():
# Make sure that Dimension objects are singletons, even when pickled
volt_dim = get_or_create_dimension((2, 1, -3, -1, 0, 0, 0))
assert volt.dim is volt_dim
import pickle
pickled_dim = pickle.dumps(volt_dim)
unpickled_dim = pickle.loads(pickled_dim)
assert unpickled_dim is volt_dim
assert unpickled_dim is volt.dim


@pytest.mark.codegen_independent
def test_str_repr():
"""
Expand Down
4 changes: 4 additions & 0 deletions brian2/units/fundamentalunits.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,10 @@ def __getstate__(self):
def __setstate__(self, state):
self._dims = state

def __reduce__(self):
# Make sure that unpickling Dimension objects does not bypass the singleton system
return (get_or_create_dimension, (self._dims, ))

### Dimension objects are singletons and deepcopy is therefore not necessary
def __deepcopy__(self, memodict):
return self
Expand Down

0 comments on commit bc94a69

Please sign in to comment.