Search code examples
pythonnumpystandardslibraries

Is using np.random bad practice for a single int?


Following from a comment on an answer I recently posted,

Any reason you are using numpy.random instead of the standard random module?

@Gulzar "Any reason not to?" - Yes: ModuleNotFoundError: No module named 'numpy'. It's bad practice to require an external library for something that can be done equally well using the standard library. Actually, the standard library would make the program slightly shorter (import random; random.randint(low_limit, high_limit + 1)).

I would like to better understand why using np.random is so much worse than just the standard random?

Reasons I preferred np.random in this case:

  1. My code base is based on numpy, never had trouble with it. Can just pip install it.
  2. It's extremely common.

Is there really something wrong with using numpy when one could use the standard? Since when is using external libraries bad practice (with 4 upvotes at the moment of posting this question)?

Examples I see as worse than the standard:

  1. Slow
  2. Unreadable
  3. Hard to incorporate into your code

Maybe I should add some items to that list?

I would like to avoid bad practices in the future :)


I hope I made this question specific enough not to be considered opinion based.
Please suggest improvements to the question instead of closing if it still is not specific enough.


Solution

  • In a ipython session with numpy already imported:

    In [1]: import random
    In [2]: random.randint(0,100)
    Out[2]: 89
    In [3]: timeit random.randint(0,100)
    1.5 µs ± 2.05 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    In [4]: timeit np.random.randint(0,100)
    5.46 µs ± 121 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    In [5]: timeit np.random.randint(0,100,1)[0]
    23.3 µs ± 1.32 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)