« Squarespace website | Main | How to root and update your htc hero. »
Thursday
Jan132011

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.

PrintView Printer Friendly Version

EmailEmail Article to Friend

References (4)

References allow you to track sources for this article, as well as articles that were written in response to this article.
  • Response
    Response: go
    Educations do not be a personal preference of parents. Children must have to be capable of adopting those fields in which they have the most interest and know their worth. If they continue their field it will surely help them in future.
  • Response
  • Response
    Response: new year songs
  • Response

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>