Sub topic 14
Common pitfalls: shadowed names and import-time side effects
This chapter assumes you know how import binds names, how sys.modules caches modules, and how sys.path is searched. Two mistakes cause many confusing import errors: giving your own file the name of another module, and running too much code when a module loads.
Shadowed module names
Python searches sys.path in order and uses the first match. When you run python script.py, the script's directory goes first on sys.path. A file in that directory with the same name as a standard library module therefore hides the real one.
Suppose you create a file called random.py next to your script:
# random.py
def pick():
return 4# main.py
import random
print(random.randint(1, 6))Running python main.py fails with AttributeError: module 'random' has no attribute 'randint'. The import succeeded, but it found your file.
A related failure happens when you name a script after a library it imports. A file called requests.py that runs import requests imports itself, and you get an error about a partially initialized module.
To diagnose a shadowing problem, print where the module came from:
import random
print(random.__file__)If the path points into your project instead of the standard library, rename your file. Delete any stale __pycache__ folder for it too. Choose names that are unlikely to collide, such as random_utils.py.
You can also shadow names without files. Binding a variable called json after import json replaces the module object in your namespace:
import json
json = {"a": 1}
print(json.dumps(json))This raises AttributeError because json is now a dictionary.
Import-time side effects
Importing a module runs its top-level code once. Anything at the top level, such as a network call, a file write, or a database connection, runs as a side effect of the import. Because of the cache, it runs on the first import only, which makes the behavior hard to predict.
# settings.py
import time
print("loading settings")
STARTED = time.time()
def get_timeout():
return 30Defining functions and constants at the top level is safe. Doing real work is not. Side effects cause these problems:
- Tests and tools that only import your module trigger the work.
- Imports become slow.
- Import order starts to matter.
- Failures raise errors during
import, far from the code that needs the result.
Move the work into a function and call it explicitly, guarded by __main__ when it is a script:
# settings.py
def load_settings():
print("loading settings")
return {"timeout": 30}
if __name__ == "__main__":
print(load_settings())Exercise
Your script test.py runs import test_helpers, but you get a surprising result and test_helpers.__file__ points to a file you did not expect. What is the likely cause, and how do you confirm it?
Show answer
Another file named test_helpers.py appears earlier on sys.path, often in the script's own directory, and shadows the intended module. Print test_helpers.__file__ and sys.path to see which entry matched first, then rename or remove the conflicting file.