Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

random.choice fails on numpy arrays #100805

Closed
Assignees
rhettinger
Labels
type-bugAn unexpected behavior, bug, or error
@NicoNeureiter

Description

@NicoNeureiter

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 aif not seq check in random.choice (line 369) that was introduced in commit3fee777. 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:

importrandomimportnumpyasnpa=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 usingif len(seq) == 0. I understand thatif 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

Linked PRs

Metadata

Metadata

Assignees

Labels

type-bugAn unexpected behavior, bug, or error

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions


    [8]ページ先頭

    ©2009-2025 Movatter.jp