how to do random / SystemRandom switch
Peter Otten
__peter__ at web.de
Sat Apr 30 09:06:34 EDT 2011
Matthias Kievernagel wrote:
> In my top-level script I want to select if my program
> is to use random.xxx functions or the random.SystemRandom.xxx
> ones. All the other modules shouldn't know about that
> switch and simply use
> import random
> ...
> return random.randint(1, 6)
> ...
> for example.
You can inject the SystemRandom instance into the sys.modules cache:
>>> import random
>>> random
<module 'random' from '/usr/lib/python2.6/random.pyc'>
>>> sr = random.SystemRandom()
>>> import sys
>>> sys.modules["random"] = sr
Then use it in the other modules:
>>> import random
>>> random
<random.SystemRandom object at 0x1acdb60>
Another approach is to monkey-patch the random module:
import random
sr = random.SystemRandom()
random.randrange = sr.randrange
random.randint = sr.randint
...
More information about the Python-list
mailing list