开发者

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

开发者 https://www.devze.com 2023-02-08 00:39 出处:网络
I need to make sure all the randomness in my program is fully replicable. Where should I place a call to random.seed()?

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 m开发者_开发问答oment 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消