Description
Bug report
In a project of mine I use random.choice on a numpy array (at multiple point in the code) which worked fine until recently. After upgrading to Python 3.11, my code crashes with:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The value error is caused by a if not seq
check in random.choice (line 369) that was introduced in commit 3fee777. The check is clearly intended to test for emptiness of the sequence and would raise an error if the sequence is empty. With numpy arrays (even non-empty ones) it now causes the ValueError when trying to cast the array to a boolean.
The issue is easily reproducible with the following code:
import random
import numpy as np
a = np.array([1, 2, 3])
random.choice(a)
The code worked on earlier versions, but fails in Python 3.11.
The problem could be avoided by checking for emptiness using if len(seq) == 0
. I understand that if not seq
checks are relatively common and many people prefer the conciseness, but numpy compatibility and backwards compatibility seem important to me in this context.
Tested on:
- CPython versions tested on: 3.11.0
- Operating system and architecture: Ubuntu 22.04 64-bit