secrets
| Use Case | Command | Description |
|---|---|---|
| π Generate secure random bytes | secrets.token_bytes(16) | Return 16 random bytes |
| π Generate URLβsafe token | secrets.token_urlsafe(16) | Return random Base64 URLβsafe string |
| π’ Generate hexadecimal token | secrets.token_hex(16) | Return random hex string |
| π² Pick a random element | secrets.choice(seq) | Choose a random element from a sequence |
| π’ Secure random integer | secrets.randbelow(n) | Return a random int in [0, n) |
| β±οΈ Timingβsafe comparison | secrets.compare_digest(a, b) | Compare two strings without leaking timing info |
https://docs.python.org/3.10/library/secrets.html
The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above.
Generate cryptographically strong pseudo-random numbers suitable for managing secrets such as account authentication, tokens, and similar.
See PEP 506 for more information. https://www.python.org/dev/peps/pep-0506/
random.Random(_random.Random)
random.SystemRandom
Alternate random number generator using sources provided by the operating system (such as /dev/urandom on Unix or CryptGenRandom on Windows).
Not available on all systems (see os.urandom() for details).
Method resolution order: SystemRandom, Random, _random.Random, builtins.object
getrandbits(self, k) β getrandbits(k) -> x. Generates an int with k random bits.getstate = _notimplemented(self, *args, **kwds)randbytes(self, n) β Generate n random bytes.random(self) β Get the next random number in the range [0.0, 1.0).seed(self, *args, **kwds) β Stub method. Not used for a system random number generator.setstate = _notimplemented(self, *args, **kwds)__getstate__(self) β # Issue 17489: Since __reduce__ was defined to fix #759889 this is no longer called; we leave it here because it has been here since random was rewritten back in 2001 and why risk breaking something.__init__(self, x=None) β Initialize an instance. Optional argument x controls seeding, as for Random.seed().__reduce__(self) β Helper for pickle.__setstate__(self, state)betavariate(self, alpha, beta) β Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1.choice(self, seq) β Choose a random element from a non-empty sequence.choices(self, population, weights=None, *, cum_weights=None, k=1) β Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability.expovariate(self, lambd) β Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called "lambda", but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative.gammavariate(self, alpha, beta) β Gamma distribution. Not the gamma function! Conditions on the parameters are alpha > 0 and beta > 0. The probability distribution function is:
x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) = --------------------------------------
math.gamma(alpha) * beta ** alphagauss(self, mu, sigma) β Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls.lognormvariate(self, mu, sigma) β Log normal distribution. If you take the natural logarithm of this distribution, you'll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero.normalvariate(self, mu, sigma) β Normal distribution. mu is the mean, and sigma is the standard deviation.paretovariate(self, alpha) β Pareto distribution. alpha is the shape parameter.randint(self, a, b) β Return random integer in range [a, b], including both end points.randrange(self, start, stop=None, step=1) β Choose a random item from range(start, stop[, step]). This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want.sample(self, population, k, *, counts=None) β Chooses k unique random elements from a population sequence or set. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. Repeated elements can be specified one at a time or with the optional counts parameter. For example:
sample(['red', 'blue'], counts=[4, 2], k=5)
is equivalent to:
sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
To choose a sample from a range of integers, use range() for the population argument. This is especially fast and space efficient for sampling from a large population:
sample(range(10000000), 60)shuffle(self, x, random=None) β Shuffle list x in place, and return None. Optional argument random is a 0-argument function returning a random float in [0.0, 1.0); if it is the default None, the standard random.random will be used.triangular(self, low=0.0, high=1.0, mode=None) β Triangular distribution. Continuous distribution bounded by given lower and upper limits, and having a given mode value in-between. http://en.wikipedia.org/wiki/Triangular_distributionuniform(self, a, b) β Get a random number in the range [a, b) or [a, b] depending on rounding.vonmisesvariate(self, mu, kappa) β Circular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi.weibullvariate(self, alpha, beta) β Weibull distribution. alpha is the scale parameter and beta is the shape parameter.__init_subclass__(**kwargs) from builtins.type β Control how subclasses generate random integers. The algorithm a subclass can use depends on the random() and/or getrandbits() implementation available to it and determines whether it can generate random integers from arbitrarily large ranges.__dict__ β dictionary for instance variables (if defined)__weakref__ β list of weak references to the object (if defined)VERSION = 3__new__(*args, **kwargs) from builtins.type β Create and return a new object. See help(type) for accurate signature.choice(seq) β Choose a random element from a non-empty sequence. (Method of random.SystemRandom instance)compare_digest(a, b, /) β Return 'a == b'. This function uses an approach designed to prevent timing analysis, making it appropriate for cryptography. a and b must both be of the same type: either str (ASCII only), or any bytes-like object. Note: If a and b are of different lengths, or if an error occurs, a timing attack could theoretically reveal information about the types and lengths of a and b--but not their values.randbelow(exclusive_upper_bound) β Return a random int in the range [0, n).randbits = getrandbits(k) β getrandbits(k) -> x. Generates an int with k random bits. (Alias for SystemRandom.getrandbits)token_bytes(nbytes=None) β Return a random byte string containing *nbytes* bytes. If *nbytes* is None or not supplied, a reasonable default is used.
>>> token_bytes(16) #doctest:+SKIP
b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b'token_hex(nbytes=None) β Return a random text string, in hexadecimal. The string has *nbytes* random bytes, each byte converted to two hex digits. If *nbytes* is None or not supplied, a reasonable default is used.
>>> token_hex(16) #doctest:+SKIP
'f9bf78b9a18ce6d46a0cd2b0b86df9da'token_urlsafe(nbytes=None) β Return a random URL-safe text string, in Base64 encoding. The string has *nbytes* random bytes. If *nbytes* is None or not supplied, a reasonable default is used.
>>> token_urlsafe(16) #doctest:+SKIP
'Drmhze6EPcv0fN_81Bj-nA'__all__ = ['choice', 'randbelow', 'randbits', 'SystemRandom', 'token_b...']
/usr/lib/python3.10/secrets.py
Generated by phpman v4.9.27 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-18 16:14 @216.73.216.114
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format