RNK
RNK

Reputation: 151

Python: AttributeError: 'module' object has no attribute 'randrange'

I know this could be caused by having a self-defined python file called random.py. I have searched for it, there is not file with such names, also there are no "pyc" file with this name.

I've also tried it by just typing the command in the terminal, and it seems to work! But it doesnt work when I try to compile the file!

Any idea what the problem might be?

Thanks!

import csv
import random
from numpy import *
from scipy.stats import norm

....

index = random.randrange(length)

...

Upvotes: 0

Views: 6418

Answers (2)

DSM
DSM

Reputation: 353559

First, you shouldn't do this on general principles:

from numpy import *

That shadows many built-ins like any and all with numpy versions which behave very differently. But in this case, it's also causing your other problem, because there's a numpy.random which is shadowing the main random module:

>>> import random
>>> random
<module 'random' from '/usr/lib/python3.4/random.py'>
>>> from numpy import *
>>> random
<module 'numpy.random' from '/usr/local/lib/python3.4/dist-packages/numpy/random/__init__.py'>

Note as an aside that if you're going to be generating many random numbers, using np.random instead of random is likely to be faster. (import numpy as np is the standard character-saving alias.)

Upvotes: 4

Jessamyn Smith
Jessamyn Smith

Reputation: 1649

It is not a best practice to import everything from modules. In this case, numpy seems to be interfering with random. When I change

from numpy import *

to

import numpy

the script runs. This would require you to reference anything you are using from numpy in the intervening code.

Upvotes: 1

Related Questions