max
max

Reputation: 52323

python 3: random.seed(): where to call it?

I need to make sure all the randomness in my program is fully replicable. Where should I place a call to random.seed()?

I thought it should be in my main.py module, but it imports other modules that happen to use random functions.

I can carefully navigate through my imports to see which one is the first to execute, but the moment I change my code structure I will have to remember to redo this analysis again.

Is there any simple and safe solution?

Upvotes: 8

Views: 5900

Answers (3)

Craig McQueen
Craig McQueen

Reputation: 43456

If you want random to be replicable, it's probably best to make an instance of random.Random in your application, call seed() on that instance, and use that instance for your random numbers.

random.random() actually uses a singleton of the random.Random class, for convenience for people who don't care enough to make their own class instance. But that singleton is potentially shared with other modules that might want to call random.random() to generate random numbers for whatever reason. That's why in your case you're better off instantiating your own random.Random instance.

Quoting from the docs:

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state.

Upvotes: 4

Jim Brissom
Jim Brissom

Reputation: 32959

It is actually safe to execute code in the "import section" of your main module, so if you are unsure about importing other modules that might or might not use the random module, maybe bypassing your seed, you can of course use something like

import random
random.seed(seed_value)

import something
import else

if __name__ == "__main__":
    main()

Upvotes: 7

Novikov
Novikov

Reputation: 4489

You could roll your own singleton that encapsulates random. You can then use Python documentation on random getstate and setstate to change the state of the random number generator. That would give your program two random number generators essentially.

Upvotes: 1

Related Questions