Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
The Python "AttributeError module 'random' has no attribute 'randint'" occurs
when we have a local file named random.py
and try to import from the random
module. To solve the error, make sure to rename any local files named
random.py
.
Here is an example of how the error occurs in a file called random.py
.
import random # ⛔️ AttributeError: module 'random' has no attribute 'randint' print(random.randint(1, 10))
The most likely cause of the error is having a local file named random.py
which shadows the random
module from the standard library.
Make sure to rename your local file to something other than random.py
to solve
the error.
import random print(random.randint(1, 10)) # 👉️ 4
You can access the __file__
property on the imported module to see whether it
is shadowed by a local file.
import random print(random.__file__) # ⛔️ result if shadowed by local file # /home/borislav/Desktop/bobbyhadz_python/random.py # ✅ result if pulling in correct module # /usr/lib/python3.10/random.py
A good way to start debugging is to print(dir(your_module))
and see what
attributes the imported module has.
Here is what printing the attributes of the random
module looks like when I
have a file random.py
in the same directory.
import random # ⛔️ ['__builtins__', '__cached__', '__doc__', '__file__', # '__loader__', '__name__', '__package__', '__spec__'] print(dir(random))
If you pass a module object to the dir() function, it returns a list of names of the module's attributes.
We can see that the imported random
module doesn't have a randint
attribute,
which makes it evident that we are shadowing the official random
module with
our local random.py
file.
If you try to import the random
module in a file called random.py
, you would
get a little different error message that means the same thing.
import random # ⛔️ AttributeError: partially initialized module 'random' has no attribute 'randint' (most likely due to a circular import) print(random.randint(1, 10))
Renaming your file solves the error.
You can use the sys
module to print all of the built-in module names if you
ever wonder if your local modules are clashing with built-in ones.
import sys # 👇️ print all built-in module names print(sys.builtin_module_names)