pfych
pfych

Reputation: 928

Cant import random python

I am having trouble importing random and randint in python

Here is the error I get when I "from random import randint"

Traceback (most recent call last):
  File "/Users/Noah/Desktop/math.py", line 2, in <module>
    from random import randint
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 45, in <module>
    from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
  File "/Users/Noah/Desktop/math.py", line 2, in <module>
    from random import randint
ImportError: cannot import name randint

and here is the error I get when "import random"

Traceback (most recent call last):
  File "/Users/Noah/Desktop/math.py", line 2, in <module>
    import random
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 45, in <module>
    from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
TypeError: 'module' object is not callable

when I go to /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7 to check the files it has random.py random.pyc and random.pyo

python is using this as the path

>>> print random.__file__
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.pyc

Edit: I have no clue what could be happening

Upvotes: 1

Views: 6876

Answers (3)

Amneet singh bhatti
Amneet singh bhatti

Reputation: 1

You should have save some file name random so the code is opening that file so try changing the name of that file

Upvotes: -1

cejno
cejno

Reputation: 1

In the same folder you have a file named math.py. You should delete this file, that is the reason it is not working. My suggestion you may delete everything in that folder.

Upvotes: 0

donkopotamus
donkopotamus

Reputation: 23206

The traceback is relatively clear:

  • you attempt to import randint from random;
  • inside the python random module it attempts to import names from math;
  • unfortunately, you chose to name one of your own modules in the working directory math as well and so it finds that first;
  • when importing your math, it attempts to import random ... now you have an circular import ... and it fails.

Conclusion:

In Python 2, don't name your modules identically to core python modules ...

Upvotes: 4

Related Questions