[Python-ideas] Globally configurable random number generation

Donald Stufft donald at stufft.io
Mon Sep 14 16:40:50 CEST 2015


On September 14, 2015 at 10:16:49 AM, Random832 (random832 at fastmail.com) wrote:
>  
> On Mon, Sep 14, 2015, at 09:51, Donald Stufft wrote:
> > I think this particular bit is a bad idea, it makes an official API
> > that makes it really hard for an auditor to come into a code base and
> > determine if the use of random is correct or not.
>  
> It's no worse than what OpenBSD itself has done with the C api for
> rand/random/rand48. At some point you've got to balance it with the
> realities of making backwards compatibility easy to achieve for the
> applications that really do need it with either a few lines change or
> none at all. And anyway, the auditor would *know* that if they see a
> module-level function called they need to do the extra work to find
> out what mode the module-level RNG is in (i.e. yes/no is there anywhere
> at all in the codebase that changes it from the secure default?)
>  
> It's not an "official API", it's an escape hatch for allowing a minimal
> change to existing code that needs the old behavior.
>  
> > Given that going back to the MT based algorithm is fairly trivial (and
> > could even be mechanical) what's the long ter benefit here?
>  
> I don't see how it's trivial/mechanical, *without* the exact feature
> being discussed.

Easily, you change your:

    import random

to

    from random import seeded_random as random

And then all of your code that used random.foo works without any further
modification. If you were importing the individual functions, you can either
change your code to use random.foo or you can do:

from random import seeded_random as _random
random = _random.random
randint = _random.randint

If you want to do this in cross language code, then you can combine this with
a try: except block like:

    try:
        from random import seeded_random as random
    except ImportError:
        import random

Either way, trivial and mechanical. It doesn't require much thought, it just
requires some pretty simple changes.

-----------------
Donald Stufft
PGP: 0x6E3CBCE93372DCFA // 7C6B 7C5D 5E2B 6356 A926 F04F 6E3C BCE9 3372 DCFA




More information about the Python-ideas mailing list