Path: csiph.com!x330-a1.tempe.blueboxinc.net!aioe.org!feeder.news-service.com!feeder.erje.net!weretis.net!feeder1.news.weretis.net!news.solani.org!.POSTED!not-for-mail From: Peter Otten <__peter__@web.de> Newsgroups: comp.lang.python Subject: Re: how to do random / SystemRandom switch Followup-To: comp.lang.python Date: Sat, 30 Apr 2011 15:06:34 +0200 Organization: None Lines: 35 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Trace: solani.org 1304168789 5745 eJwNyskBwDAIA7CVaoI5xqEU9h8h1Vs8BmtXoymXi+PZHVPY8VJMMUpC1ZYA7RP8aWXyeVOdFxsNEKg= (30 Apr 2011 13:06:29 GMT) X-Complaints-To: abuse@news.solani.org NNTP-Posting-Date: Sat, 30 Apr 2011 13:06:29 +0000 (UTC) X-User-ID: eJwNyMkRAzEMA7CWrIt0ytFQVv8lbPBEBQxiopC1taIxOfx39HrdGvXT6KIDB3atf7N1FPR0YubF6TVHuOZ9R+QVWg== Cancel-Lock: sha1:5yVU+ZG8QUg9+aFYuMYVrGX/zAM= X-NNTP-Posting-Host: eJwNyrEBACEIBLCV4OUOHQcE9h/h7VIEi8rrRtAwmE9s8ny2Kb4AyYtCRPJRQjVaqHq2Oc5IV1KjLoKyRjY609DdLA++iB+qmxl1 Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:4198 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 ...