简体   繁体   中英

How to use Python's random number generator with a local seed?

Python's random seems are global, so modules changing it will effect each other.

While there are of course many 3rd party modules, is there a way using Python's standard library to have a random number local to a context.

(without using random.get/setstate which may be problematic when mixing code from different modules).

Something like...

r = random.context(seed=42)
number = r.randint(10, 20)

Where each module can use its own random context.

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.

Make your own random.Random instance and use that.

rng = random.Random(42)
number = rng.randint(10, 20)

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