python / python/cpython

Support __index__() in getrandbits(), randbytes() and others

Open
#135,378 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

pending stdlib type-feature
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Feature or enhancement

Support of the __index__() method in getrandbits() and randbytes() is inconsistent.

  • Random.getrandbits() supports __index__(), but SystemRandom.getrandbits() does not.
  • SystemRandom.randbytes() supports __index__(), but Random.randbytes() does not.

For consistence, both classes should support it.

sample() fails if its k argument is not integer. k should have __index__(), but it also should support comparison with integers and multiplication by list and integer. It is easy to make it more general, and only require __index__(). It will also produce more meaningful error.

binomialvariate() seems "working" with non-integer n argument, but the result is questionable. Passing non-integer value is most likely an error, and it would be better to detect it.

cc @rhettinger

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Locate the implementations and tests for Random.getrandbits(), SystemRandom.getrandbits(), Random.randbytes(), SystemRandom.randbytes(), sample(), and binomialvariate(). Compare their handling of non-integer arguments, then verify that supported arguments consistently use index() and invalid binomialvariate() inputs are rejected.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.