random.seed() and python module imports

Interesting factoid on the random library.
I use random.seed() in my tests to get reproducible numbers (to test graphing and stats functions) and I have found the following unexpected behavior.
>>> import random
imports the random library as a singleton therefore, if you write:
>>> random.seed(0)
it will actually set a seed for all code (including library code) that uses the random library. Worse than that if your test code calls a library that uses random it will get a number from that sequence and now the random numbers in your tests are not in the same sequence as they may have been without the library call (this is the problem that caused me to think about this)
Therefore my blanket recommendation for all code that uses random.seed() is that the import line be changed to the following:
>>> from random import Random
>>> random = Random()
this will give you a new instance of random that will only be used within your module scope, and all previous calls to random.seed() etc will continue to work.



Reader Comments