Skip to main content

How to Resolve NameError and AttributeError for random Module in Python

When using Python's powerful random module for generating random numbers or making choices, beginners and even experienced developers can encounter errors like NameError: name 'random' is not defined or AttributeError: module 'random' has no attribute 'randint'.

These typically arise from either forgetting to import the module or accidentally creating a filename conflict.

This guide explains the causes of these common random module errors and provides clear solutions.

Error 1: NameError: name 'random' is not defined (or specific function like 'randint')

This error means Python doesn't recognize the name random (or a specific function name like randint) in the current scope because it hasn't been imported or defined.

Cause: Module or Function Not Imported

Even though random is part of Python's standard library, you must explicitly import it (or the specific functions you need from it) before using them in your script.

# Error Scenario: 'random' not imported
try:
# ⛔️ NameError: name 'random' is not defined
random_number = random.randint(1, 10)
print(random_number)
except NameError as e:
print(e)

# Error Scenario: 'randint' not imported directly
try:
# ⛔️ NameError: name 'randint' is not defined
another_number = randint(1, 5) # Called directly without 'random.' prefix
print(another_number)
except NameError as e:
print(e)

Solution 1: Import the Entire random Module (import random)

Import the entire module at the top of your file. You then access functions using the random. prefix.

# ✅ Import the whole module
import random

# Access functions via the module name prefix
n1 = random.randint(1, 10)
print(f"Random int: {n1}")

s1 = random.choice(['apple', 'banana', 'cherry'])
print(f"Random choice: {s1}")

Make sure the import statement (import random) is placed at the top level of your script, before any code that uses the module.

Alternatively, and often preferred for clarity, import only the specific functions you need directly into your script's namespace.

# ✅ Import only specific functions needed
from random import randint, choice, shuffle

# Call functions directly without the 'random.' prefix
n1 = randint(1, 10) # No prefix needed
print(f"Random int: {n1}")

s1 = choice(['apple', 'banana', 'cherry']) # No prefix needed
print(f"Random choice: {s1}")

my_list = [1, 2, 3, 4]
shuffle(my_list) # No prefix needed
print(f"Shuffled list: {my_list}")

This approach makes it clearer exactly which functions from the module are being used in your code.

Pitfall: Importing in Incorrect Scopes

Avoid importing modules inside functions or try...except blocks unless you have a very specific reason (like optional dependencies or preventing circular imports, which are advanced topics). Imports within a function are local to that function's scope. Imports within a try block might fail if an earlier line in the try raises an exception.

# --- Problem: Import inside function ---
def generate():
import random # Imported only inside this function
print(random.randint(100, 200))

generate() # Works fine

try:
# ⛔️ NameError: name 'random' is not defined
# random was imported only inside generate(), not in the global scope
print(random.choice(['x', 'y']))
except NameError as e:
print(f"Error: {e}")

# --- Problem: Import inside try that might fail ---
try:
value = 1 / 0 # This will raise ZeroDivisionError
import random # This line might not be reached
print("Imported random inside try")
except ZeroDivisionError:
print("Caught division error")

try:
# ⛔️ NameError: name 'random' is not defined
# The import might not have happened if the ZeroDivisionError occurred
print(random.randint(1, 5))
except NameError as e:
print(f"Error: {e}")

# ✅ Solution: Move imports to the top level
import random # Import here

def generate_fixed():
print(random.randint(100, 200)) # Uses globally imported random

generate_fixed()
print(random.choice(['x', 'y'])) # Works!

Error 2: AttributeError: module 'random' has no attribute '...' (e.g., 'randint', 'choice')

This error usually means Python found something named random when you did import random, but it's not the standard library module you expected. Therefore, it doesn't have the attributes (functions) like randint or choice.

Cause: Local File Named random.py (Shadowing)

The most common cause is that you have named your own Python script random.py in the same directory you are working in. When Python executes import random, it checks the current directory before checking standard library locations. It finds your random.py, imports that file, and ignores the built-in random module. Your local file likely doesn't define randint, choice, etc., leading to the AttributeError.

random.py
# --- Code inside a file named random.py ---
import random # Imports THIS FILE, not the library!

# Some other function in your file
def my_function():
print("This is my function.")

try:
# ⛔️ AttributeError: module 'random' has no attribute 'randint'
# The imported 'random' is this file, which doesn't have randint.
print(random.randint(1, 10))
except AttributeError as e:
print(e)

try:
# ⛔️ AttributeError: module 'random' has no attribute 'choice'
print(random.choice([1, 2, 3]))
except AttributeError as e:
print(e)

Solution: Rename Your Local random.py File

The solution is straightforward: Rename your file to something else, like my_random_stuff.py, app.py, main.py, or anything that doesn't conflict with a standard library module name.

Once renamed, the import random statement in your (renamed) script will correctly find and load the standard library module.

main.py
# --- Code inside a file named main.py (or similar) ---
import random # Now correctly imports the standard library module

# Now these work as expected
print(random.randint(1, 10))
print(random.choice(['a', 'b', 'c']))

Debugging: Identifying the Conflict (__file__, dir())

If you suspect a filename conflict, you can verify which module was actually imported:

  • Check __file__ attribute:

    import random
    print(random.__file__)
    • Problem: If the output path points to your project directory (e.g., /path/to/your/project/random.py), you've imported your local file.
    • Correct: If the path points to the Python standard library installation (e.g., /usr/lib/python3.10/random.py or similar in site-packages or a virtual environment), the correct module was imported.
  • Check dir() output:

    import random
    print(dir(random))
    • Problem: If the output is a short list containing mainly internal names (__name__, __file__, etc.) and perhaps functions you defined in your random.py, it's the wrong module.
    • Correct: If the output is a long list containing many functions like randint, choice, shuffle, uniform, seed, etc., it's the correct standard library module.

Sometimes, inside your conflicting random.py file, you might see a slightly different error like: AttributeError: partially initialized module 'random' has no attribute 'randint' (most likely due to a circular import)

This happens because random.py tries to import random, causing it to import itself before it's fully loaded. The solution is the same: Rename your random.py file.

Conclusion

Errors involving Python's random module typically fall into two categories:

  1. NameError: Caused by forgetting to import random or from random import function_name. Ensure imports are present and at the top level of your script. Using from random import ... is often clearer.
  2. AttributeError: Usually caused by a local file named random.py shadowing the standard library module. Rename your local file to fix this. Use random.__file__ and dir(random) to confirm which module is being imported if you suspect this issue.

By understanding these common pitfalls, you can use the random module effectively and troubleshoot these errors quickly.