Path: csiph.com!x330-a1.tempe.blueboxinc.net!aioe.org!.POSTED!not-for-mail From: Matthias Kievernagel Newsgroups: comp.lang.python Subject: Re: how to do random / SystemRandom switch Date: Sat, 30 Apr 2011 13:28:36 +0000 (UTC) Organization: Aioe.org NNTP Server Lines: 41 Message-ID: References: NNTP-Posting-Host: 64lgluVpOUrep19B1JyNDw.user.speranza.aioe.org X-Complaints-To: abuse@aioe.org User-Agent: tin/1.9.3-20080506 ("Dalintober") (UNIX) (Linux/2.6.26-2-686 (i686)) X-Notice: Filtered by postfilter v. 0.8.2 Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:4199 Peter Otten <__peter__@web.de> wrote: > 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 > >>>> sr = random.SystemRandom() >>>> import sys >>>> sys.modules["random"] = sr > > Then use it in the other modules: > >>>> import random >>>> random > > > Another approach is to monkey-patch the random module: > > import random > sr = random.SystemRandom() > random.randrange = sr.randrange > random.randint = sr.randint > ... > Thanks a lot. That's what I was looking for. I'll give both a try. Regards, Matthias Kievernagel