D1ag0
D1ag0

Reputation: 41

module 'random' has no attribute 'random'

I have read some other questions from stackoverflow, all they need to do it change file name to something else, but my file name is different already:

import random

x = random.random()

print(x)

and I got error like:

Traceback (most recent call last):
  File "math.py", line 1, in <module>
    import random
  File "/anaconda3/lib/python3.6/random.py", line 42, in <module>
    from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
  File "/Users/pgao/Documents/Python Project/math.py", line 3, in <module>
    x = random.random()
AttributeError: module 'random' has no attribute 'random'

please help me with this simply question, i am selfstudy python language recently. thanks.

Upvotes: 0

Views: 2468

Answers (2)

Cireo
Cireo

Reputation: 4427

On the contrary, you've managed to shoot yourself in the foot by naming your file not random.py but math.py, which is also a builtin, and which random imports.

The traceback is exactly correct (thanks for including it!). When random tries to figure out what it is defined as, it imports math, which resolves to your original file. Your original file then tries to figure out what it is (again), but there is a placeholder for random (only 42 lines are evaluated so far), and it doesn't have any random.random attribute.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

The problem is that the random module imports the math module, and since you named your own source file math.py it's what will be imported.

Rename your source file to something else.

Upvotes: 4

Related Questions