Skip to content

Commit eb0fcf8

Browse files
raise ValueError when Distribution is initialized with a 0-length dimension
1 parent 81465b0 commit eb0fcf8

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

pymc3/distributions/distribution.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,12 @@ def __new__(cls, name, *args, **kwargs):
107107
dims = (dims,)
108108
shape = model.shape_from_dims(dims)
109109

110+
# failsafe against 0-shapes
111+
if shape is not None and any(np.atleast_1d(shape) <= 0):
112+
raise ValueError(
113+
f"Distribution initialized with invalid shape {shape}. This is not allowed."
114+
)
115+
110116
# Some distributions do not accept shape=None
111117
if has_shape or shape is not None:
112118
dist = cls.dist(*args, **kwargs, shape=shape)

pymc3/tests/test_distributions_random.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,9 @@ def test_scalar_distribution_shape(self, shape, size):
264264
assert (
265265
expected == actual
266266
), f"Sample size {size} from {shape}-shaped RV had shape {actual}. Expected: {expected}"
267+
# check that negative size raises an error
268+
with pytest.raises(ValueError, match="not allowed"):
269+
rv.random(size=-2)
267270

268271
@pytest.mark.parametrize("size", [None, ()], ids=str)
269272
@pytest.mark.parametrize(
@@ -293,6 +296,11 @@ def test_vector_params(self, shape, size):
293296
expected == actual
294297
), f"Sample size {size} from {shape}-shaped RV had shape {actual}. Expected: {expected}"
295298

299+
@pytest.mark.parametrize("shape", [-2, 0, (0,), (2, 0), (5, 0, 3)])
300+
def test_shape_error_on_zero_shape_rv(self, shape):
301+
with pytest.raises(ValueError, match="not allowed"):
302+
self.get_random_variable(shape)
303+
296304

297305
class TestGaussianRandomWalk(BaseTestCases.BaseTestCase):
298306
distribution = pm.GaussianRandomWalk

0 commit comments

Comments
 (0)