简体   繁体   中英

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?

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()

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM