[Tutor] How to test function using random.randint()?

Ben Finney ben+python at benfinney.id.au
Sun Mar 20 21:44:14 EDT 2016


boB Stepp <robertvstepp at gmail.com> writes:

> On Sun, Mar 20, 2016 at 8:19 PM, Ben Finney <ben+python at benfinney.id.au> wrote:
> >     if rng is None:
> >         rng = random._inst
> >
> > which is the default RNG instance in the module.
>
> Can I not use:
>
> if rng is None:
>     rng = random.Random()

That will work.

It unfortunately creates a new random.Random instance every time that
line is executed, making the function waste a lot of time.

So instead, you many want to create a module-level instance, and refer
to that as the default.

    # die_roller.py

    """ Functionality for rolling numbers from polyhedral dice. """

    import random

    rng = random.Random()

    def roll_die(num_sides, rng=rng):
        # …

-- 
 \       “Give a man a fish, and you'll feed him for a day; give him a |
  `\    religion, and he'll starve to death while praying for a fish.” |
_o__)                                                       —Anonymous |
Ben Finney



More information about the Tutor mailing list