Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Lib/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def _urandom(*args, **kwargs):
"randrange","shuffle","normalvariate","lognormvariate",
"expovariate","vonmisesvariate","gammavariate","triangular",
"gauss","betavariate","paretovariate","weibullvariate",
"getstate","setstate", "getrandbits", "choices",
"getstate","setstate", "getrandbits", "randbytes", "choices",
"SystemRandom"]

NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0)
Expand Down Expand Up @@ -775,6 +775,7 @@ def _test(N=2000):
getstate = _inst.getstate
setstate = _inst.setstate
getrandbits = _inst.getrandbits
randbytes = _inst.randbytes

if hasattr(_os, "fork"):
_os.register_at_fork(after_in_child=_inst.seed)
Expand Down
13 changes: 11 additions & 2 deletions extra_tests/snippets/stdlib_random.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import random
import random

random.seed(1234)

Expand All @@ -14,7 +14,7 @@
# random.choice
assert random.choice(left) == 5

# random.choices
# random.choices
expected = ['red', 'green', 'red', 'black', 'black', 'red']
result = random.choices(['red', 'black', 'green'], [18, 18, 2], k=6)
assert expected == result
Expand All @@ -23,6 +23,15 @@
sampled = [0, 2, 1]
assert random.sample(list(range(3)), 3) == sampled

# random.randbytes
random.seed(1234)
zero_size_buf = random.randbytes(0)
assert type(zero_size_buf) is bytes
assert len(zero_size_buf) == 0
non_zero_buf = random.randbytes(4)
assert type(non_zero_buf) is bytes
assert list(non_zero_buf) == list(b'\xb9\x7fi\xf7')
Comment on lines +26 to +33

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Try experimenting with testutils.skip_if_unsupported (defined here). Here's an example of it in action.


# TODO : random.random(), random.uniform(), random.triangular(),
# random.betavariate, random.expovariate, random.gammavariate,
# random.gauss, random.lognormvariate, random.normalvariate,
Expand Down
8 changes: 8 additions & 0 deletions stdlib/src/random.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,5 +144,13 @@ mod _random {
};
Ok(BigInt::from_biguint(sign, uint))
}

#[pymethod]
fn randbytes(&self, n: usize) -> PyResult<Vec<u8>> {
let mut buf = vec![0u8; n];
let mut rng = self.rng.lock();
rng.fill_bytes(&mut buf);
Ok(buf)
}
}
}