Main Ecosystems
HomePython CorePandas ReferenceNumPy ScientificFastAPI & PydanticDjango Enterprise
More Ecosystems
Environment & SetupRequests & HTTPAsyncIO ConcurrencyObject-Oriented OOPPyTorch Deep LearningScikit-Learn MLFlask FrameworkWeb ScrapingDatabase & ORMDevOps & Docker

Python Requests: ModuleNotFoundError: No module named requests.auth and File Shadowing

Verified FixPython 3.10+Requests 2.31+Silo: requests

Quick Fix / Solution Rapide

This error occurs when Python tries to import requests.auth but resolves a local file named requests.py in the current directory instead of the installed package. Rename local requests.py to a non-colliding name and delete pycache.

Root Cause Analysis

This error occurs when Python attempts to import a submodule or subpackage from the third-party requests library (such as requests.auth or requests.exceptions), but finds a local file named requests.py in the current working directory that shadows the installed library.

Root Cause 1: Python Module Search Path (sys.path) Priority

When Python executes a script, it automatically prepends the directory containing the script (or the current working directory '') to sys.path as the highest priority search location. If a developer creates a test file named requests.py, any statement executing import requests or from requests.auth import HTTPBasicAuth will load the local requests.py single-file module rather than the third-party package in site-packages.

Root Cause 2: Single-File Module vs Package Namespace

The official requests library is a package (a directory containing an __init__.py and submodules like auth.py, models.py, sessions.py). A local requests.py file is a single module without a package namespace. Attempting to access requests.auth on a single-file module triggers ModuleNotFoundError: No module named 'requests.auth'; 'requests' is not a package.

Root Cause 3: Stale Bytecode Cache Files (pycache)

Even after deleting or renaming requests.py, a compiled bytecode file (such as requests.cpython-312.pyc) may remain in the __pycache__ folder. Python may continue loading the stale cached module, persisting the ModuleNotFoundError.

Root Cause 4: Virtual Environment Isolation Issues

If the active virtual environment does not have requests installed, Python may traverse up the system path or fail immediately, producing similar module resolution errors.

Reproduction Code (MCVE)

Example: Bug Reproduction
import sys

# Simulating module namespace collision caused by a local file named requests.py
class MockLocalShadowModule:
    """Shadows the third-party requests package with a local script."""
    __file__ = "C:\projects\my_script\requests.py"
    __path__ = []

sys.modules["requests"] = MockLocalShadowModule()

# Attempting to access requests.auth on single-file local module triggers ModuleNotFoundError
if not hasattr(sys.modules["requests"], "auth"):
    raise ModuleNotFoundError("No module named 'requests.auth'; 'requests' is not a package")

Solution 1: Rename the Local Script and Import from requests.auth

Rename the colliding local script (e.g. test_api.py instead of requests.py), remove __pycache__, and import HTTPBasicAuth directly from requests.auth.

Example: Recommended Solution
import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth

# Solution 1: Import directly from the installed requests library (after renaming local requests.py)
auth_handler = HTTPBasicAuth("admin_user", "secure_password_123")
print("HTTPBasicAuth initialized:", type(auth_handler).__name__)

# Test authentication object properties
assert auth_handler.username == "admin_user"
assert auth_handler.password == "secure_password_123" 

Solution 2: Use Tuple Shorthand for HTTP Authentication

Pass authentication credentials directly as a tuple (username, password) to requests functions without explicit auth class imports.

Example: Alternative Solution
import requests

# Solution 2: Pass auth tuple directly to requests methods
credentials = ("api_key_user", "secret_token_val")

def build_auth_config(creds: tuple):
    return {"auth": creds, "status": "configured"}

res = build_auth_config(credentials)
print("Auth configuration:", res)
assert res["auth"][0] == "api_key_user" 

Module shadowing is one of the most common pitfalls for beginners in Python. Naming scripts test.py, email.py, json.py, random.py, csv.py, or requests.py will break core standard library modules or third-party packages throughout your script. Always adopt a naming convention such as test_requests_client.py or demo_json_parsing.py.

Another edge case is having an empty __init__.py file in your project root that unintentionally turns your working directory into an unintended top-level package.

Contrast ModuleNotFoundError: No module named 'requests.auth' with AttributeError: module 'requests' has no attribute 'auth': ModuleNotFoundError occurs during import statement resolution, while AttributeError occurs when accessing an un-imported submodule as an attribute on the module object.