Validate empty shapes before multiplying dimensions in Python
A missing shape can silently produce a size of one when dimensions are multiplied. Decide whether an empty shape is meaningful before using the result to allocate storage.
Run the example
Tested on Linux with Python 3.12.14. No third-party packages are required. In one Bash session, create a disposable directory:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Save this as demo_python_prod_empty_shape_validation.py. Use that filename to avoid shadowing a standard-library module.
from math import prod
def cell_count(shape):
dimensions = tuple(shape)
if not dimensions:
raise ValueError("shape must contain at least one dimension")
if any(type(n) is not int or n < 0 for n in dimensions):
raise ValueError("dimensions must be nonnegative integers")
return prod(dimensions)
print("raw empty product:", prod([]))
for shape in ((3, 4, 2), (3, 0), (), (3, -1), (3, True)):
try:
print(f"{shape!r}: {cell_count(shape)} cells")
except ValueError as error:
print(f"{shape!r}: {error}")Run it:
python3 demo_python_prod_empty_shape_validation.pyOutput:
raw empty product: 1
(3, 4, 2): 24 cells
(3, 0): 0 cells
(): shape must contain at least one dimension
(3, -1): dimensions must be nonnegative integers
(3, True): dimensions must be nonnegative integersThe empty product is the multiplicative identity, one. That convention is useful for scalar shapes, but this application requires at least one dimension. A zero dimension remains valid and produces zero cells. Validation checks every dimension before computing the product, so a zero does not conceal a later invalid value.
Input policy and limits
Materializing the shape makes a finite iterator reusable for validation and multiplication. Supply a bounded sequence; this wrapper is not suitable for an infinite iterator. Python integers can hold a large product, but memory allocation still needs a separate size limit.
Clean up
In the same Bash session, remove the source file and the empty working directory:
rm -- demo_python_prod_empty_shape_validation.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf the directory is not empty, inspect its contents before deleting anything else.
References
Acknowledgements
This post was created with assistance from AI.