Skip to content

numpy/rng-in-loop

Rule rng-in-loop
Pack NumPy
Severity warning
Fix none, edit by hand
Library versions every version

np.random.default_rng() inside a loop builds a new Generator on every pass. Create it once before the loop and draw from it.

noise = [np.random.default_rng().normal() for _ in range(n)]
rng = np.random.default_rng()
noise = rng.normal(size=n)

The rule reports np.random.default_rng() without a seed inside a for or while body or a comprehension. Each call gathers entropy, the random bits for a seed, from the operating system, which takes about 5 microseconds. The rule leaves a loop alone that seeds each pass from its loop variable.

xpd has no automatic fix, so make the change by hand.

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

$NP.random.default_rng() builds a new Generator on every pass, which costs about 5 microseconds each time. Create rng = $NP.random.default_rng() once before the loop and draw from it.

Browse the other rules of the NumPy pack.