← 输入框|github.com|刷新
Skip to content

Add random.randbool for Bernoulli distribution over bool #162817

Backlog

Description

@George-Ogden

Feature or enhancement

Generate a random bool in Python with a given probability.

Main Problem

The correct way to generate a random boolean (from a Bernoulli distribution) in Python is random.random() < p.
This is easy to get wrong and write random.random() <= p, which would generate True very occasionally with p == 0.0.
Or even worse, you might accidentally write p < random.random().

Secondary Problem

There also isn't an obvious way to generate a uniform boolean value:

random.random() < 0.5 # canonical
random.random() >= 0.5 # equivalent
random.random() >/<= 0.5 # close enough
random.choice([True, False]) # or [False, True] or (True, False)
bool(random.randint(0, 1)) # :(
bool(random.binomialvariate()) # or you could add arguments
# More creative ones exist.

Proposed Function

I would like to add a random boolean function to the standard library.

def randbool(p: float = 0.5) -> bool:
    if not 0.0 <= p <= 1.0: # excludes NaN probabilities, but also works with integers
        raise ValueError(f"Random value should between 0 and 1, got {p}.")
    return random.random() < p

Before adding a this feature, I want to get a consensus, because I predict that people will not like it or bits of it.

The Name

I propose randbool which matches randint and randrange in its style.
It also means that searching (ctrl+f) bool on the random documentation page returns this function.
Rust uses the name random_boolean for the same functionality.
Java and Kotlin use nextBoolean, but these do not specify the probability.
Swift uses random and Julia uses rand, again without a probability, but specifying that the type is boolean.
C++ uses bernoulli_distribution and SciPy uses bernoulli, but these return distributions, not booleans.
JavaScript, Go, C# and NumPy do not have direct ways to generate random booleans.

This name is unambiguous to anyone reading the code.
Alternatives I considered, but rejected:

  • ...boolean: Python has the type bool, not boolean.
  • random_bool: it matches the Rust but doesn't match the rest of the random library.
  • bernoullivariate: this fits in with binomialvariate and betavariate but is confusing to those unfamiliar with the depths of the random library; it's also not easily searchable.

The Signature

The random.randint function accepts a and b as its parameters.
The binomialvariate function also abbreviates its probability to p, the other argument is n.
p is a fairly unambiguous name (what else could it be?) and prob or probability are unnecessarily verbose.
I also considered a positional only argument, which would allow changing the name, but I felt this was again overcomplicating things.
The default value of ½ gives a uniform distribution when p is not given; binomialvariate defaults to p=0.5 too.
The types will be omitted in the standard library.

Further Justifications

Searching GitHub for this pattern random.random() < lang:python reveals 1.5M code results.
Most of them use the canonical version, but there are some errors.
This version:

  • is explicit (Explicit is better than implicit.)
  • is readable (Readability counts.)
  • creates one obvious way to do this (There should be one-- and preferably only one --obvious way to do it.)

I'm interested to hear others' thoughts.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

Duplicates

Apologies if this has already been proposed. I couldn't find anything searching on both GitHub issue and discussions:

  • random bool label:stdlib
  • bernoulli

Linked PRs

Activity

  1. added
    type-feature
    on Nov 28, 2026
  2. picnixz commented on Nov 28, 2026

    @picnixz
    Member

    We are quite reticent to extend the interface of random.Random in general, whether it's by changing it to C implementations or adding more methods. I think we can add it as a doc recipe first that people can just copy. If we were to add it, I would rather prefer it as a random.bernoullivariate or use random.choices() (though randbool is still fine).

    Now, that being said, I don't think we need it because people seem to do it already correctly?

    cc @rhettinger

  3. added
    stdlib
    pending
    on Nov 28, 2026
  4. changed the title [-]`random.randbool` Proposal[/-] [+]Add `random.randbool` for Bernoulli distribution over `bool`[/+] on Nov 28, 2026
  5. skirpichev commented on Nov 29, 2026

    @skirpichev
    Member

    Don't forget, that the random module docs has Recipes section. One possibility is to add a new snippet(s?) here.

  6. George-Ogden commented on Nov 29, 2026

    @George-Ogden
    ContributorAuthor

    Adding it to the recipes section is a reasonable alternative, but this feels like a fundamental thing that a random library should have. That being said, it's quite uncommon to see this in other languages.

  7. picnixz commented on Nov 29, 2026

    @picnixz
    Member

    i would rather see it in a recipe first

  8. George-Ogden commented on Nov 29, 2026

    @George-Ogden
    ContributorAuthor

    @picnixz, I have created #162836 - is there a way I can allocate you/someone else as the reviewer, please?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingstdlibtype-feature

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions