Skip to content

Commit

Permalink
Prevent seed and random from being shared between instances
Browse files Browse the repository at this point in the history
This commit aims to change two related issues:

- New instances of a model should not be able to overwrite the value of the
seed of previous (and possibly running) models.
- The `random` attribute should be instance-level, not class-level.

Prior to this commit, both `_seed` and the `random` were class attributes that
were set/changed every time a new instance was created.

This fixes #1438
  • Loading branch information
balkian authored and rht committed Oct 5, 2022
1 parent 3def79d commit 478a66b
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
7 changes: 4 additions & 3 deletions mesa/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ class Model:

def __new__(cls, *args: Any, **kwargs: Any) -> Any:
"""Create a new model object and instantiate its RNG automatically."""
cls._seed = kwargs.get("seed", None)
cls.random = random.Random(cls._seed)
return object.__new__(cls)
obj = object.__new__(cls)
obj._seed = kwargs.get("seed", None)
obj.random = random.Random(obj._seed)
return obj

def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Create a new model. Overload this method with the actual code to
Expand Down
3 changes: 3 additions & 0 deletions tests/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ def step(self):
def test_seed(seed=23):
model = Model(seed=seed)
assert model._seed == seed
model2 = Model(seed=seed + 1)
assert model2._seed == seed + 1
assert model._seed == seed


def test_reset_randomizer(newseed=42):
Expand Down

0 comments on commit 478a66b

Please sign in to comment.