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. It covers two families of bugs that come from those mechanisms: names that resolve to the wrong object, and code that does too much work when a module loads.
Shadowed module names
A name is shadowed when a different object answers to it than the one you meant. For imports, the most common cause is a file in your own project that has the same name as another module.
Your file hides a standard library module
Python searches sys.path in order and uses the first match. When you run a script, the script's directory is placed first on sys.path. A local file named random.py therefore wins over the standard library random.
# random.py (your own file, in the same folder as main.py)
def pick():
return 4# main.py
import random
print(random.randint(1, 6))Running python main.py fails with an error like this:
AttributeError: module 'random' has no attribute 'randint' (consider renaming '/home/you/project/random.py' because it has the same name as the standard library module named 'random' ...)The message names the file that was imported. Newer Python versions add the "consider renaming" hint. Older versions only say has no attribute, so check __file__ yourself.
A related variant is a circular-looking failure: import random inside your own random.py. The file imports itself, and the half-built module has no attributes yet.
Diagnosing which file was imported
Print the module's __file__ and __spec__ to see where it came from.
import json
print(json.__file__)
print(json.__spec__.origin)
print(json.__spec__.loader)For a standard library module, the path points into the Python installation. If it points into your project, you have a shadowing problem. You can also list the first entries of the search path:
import sys
for entry in sys.path[:4]:
print(repr(entry))Typical names to avoid are random.py, json.py, email.py, types.py, test.py, string.py, logging.py, queue.py, and typing.py. You can check a candidate name with sys.stdlib_module_names, available in Python 3.10 and later.
import sys
for name in ("random", "mytools", "queue"):
print(name, name in sys.stdlib_module_names)Stale bytecode and leftover files
Deleting or renaming a shadowing file does not always fix the problem at once. A __pycache__ folder may hold compiled files, and a leftover random/ directory (even an empty one) can be picked up as a namespace package. After renaming, remove the old __pycache__ entries and any stray directory with the same name, then restart the interpreter.
Shadowing a module with a variable
Shadowing also happens after the import, inside a namespace. A later assignment rebinds the name, and the module is no longer reachable through it.
import json
json = {"name": "Ada"} # rebinds the name json
try:
json.dumps(json)
except AttributeError as exc:
print(exc)The same happens with from imports. If two imports bring in the same name, the later one wins without any warning.
from math import pow
from os import * # os has no pow today, but star imports can overwrite names silently
print(pow(2, 3))Prefer import module over from module import *. The star form hides where a name came from and can overwrite names you already bound. Keep star imports out of application code. If you use one inside a package's __init__.py, control its effect with __all__.
A built-in can be shadowed in the same way. from numpy import * historically replaced sum, min, and max with different functions. A module-level variable named list or id has a similar effect on every function in that file.
| Symptom | Likely cause | Fix |
|---|---|---|
| `module has no attribute` for a standard library function | A local file has the same name as the module | Rename your file, delete stale `__pycache__` |
| `X object is not callable` after an import | A later assignment or import rebound the name | Rename the variable, or use `import module` |
| Different behavior depending on the folder you run from | `sys.path[0]` changes with the working script | Run with `python -m package.module` from the project root |
| `ImportError: cannot import name` with a name that exists | A cycle, or a file shadows the package | Check `__file__`, then see the circular imports chapter |
Import-time side effects
Importing a module executes its top-level code once. Anything at that level, such as opening files, reading environment variables, making network calls, or starting threads, runs on import, before any function of yours is called.
What goes wrong
Side effects at import time cause several problems:
- Importing the module for a test or for documentation tools triggers real work.
- Errors appear at
importinstead of at the call that needs the resource, which makes tracebacks confusing. - Import order starts to matter, because one module's side effect may be required by another.
- The result is cached in
sys.modules, so the work runs once and its result is frozen for the whole process.
Here is a module with a harmful side effect:
# config_bad.py
import os
print("loading config") # output on import
DATABASE_URL = os.environ["DATABASE_URL"] # KeyError at import if unset
connection = open("/var/log/app.log", "a") # opens a file on importAnyone who runs import config_bad without DATABASE_URL set gets a KeyError from a line they did not write. A module that fails during import is removed from sys.modules, so a second attempt re-runs everything.
Move work into functions
The usual fix is to define things at import time and do the work when asked.
# config_good.py
import os
from functools import lru_cache
@lru_cache(maxsize=None)
def database_url():
try:
return os.environ["DATABASE_URL"]
except KeyError:
raise RuntimeError("Set DATABASE_URL before connecting") from None
def main():
print(database_url())
if __name__ == "__main__":
main()Importing config_good now has no effect. The environment lookup happens on the first call and is cached after that. The __main__ guard from the earlier chapter keeps script behavior out of the import path.
Not all import-time work is a problem. Defining functions and classes, setting constants, and building small lookup tables are the normal purpose of top-level code. The line to draw is between cheap, deterministic setup and anything that touches the outside world or takes noticeable time.
Mutable state shared through the cache
Because sys.modules returns the same object to every importer, module-level mutable values are shared across the whole program.
# registry.py
handlers = []
def register(fn):
handlers.append(fn)
return fnEvery module that does import registry sees the same handlers list. That is useful for plugin registries and a hazard in tests, where state from one test leaks into the next. Reset such state in a fixture, or hide it behind a function that creates a fresh object.
A subtler case is a module imported under two names. If the same file is reachable as both app.utils and utils (for example because both the project root and app/ are on sys.path), Python loads it twice. You then get two module objects, two copies of every global, and isinstance checks that fail across them.
import sys
# Shows every cached name that ends with "utils"; two entries for one file signal a double import.
print([name for name in sys.modules if name.split(".")[-1] == "utils"])The fix is to pick one import root, use absolute imports from it, and never add a package's own directory to sys.path.
Timing slow imports
When startup is slow, measure it. Python can report the time spent on each import.
python -X importtime -c "import json"The output lists self time and cumulative time per module in microseconds, on standard error. A heavy import that is only needed in one function can be moved inside that function, which is the deferred import pattern shown earlier for circular imports. Weigh that against the cost: errors then surface late, and the import line is no longer visible at the top of the file.
A checklist before you commit
- Does any file or folder in the project share a name with a standard library module? Compare against
sys.stdlib_module_names. - Does any module run network, file, or environment work at its top level? Move it into a function.
- Are you using
from x import *outside an__init__.pythat defines__all__? - Is any file reachable under two import names?
- Do your tests reset module-level mutable state?
Exercise
You create a file queue.py next to main.py. Running main.py fails with AttributeError: module 'queue' has no attribute 'Queue', although your code never imports your own queue.py. Explain the cause, give two steps to confirm it, and give the fix.
Show answer
Python puts the script's directory first on sys.path, so import queue (made by main.py or by a library such as threading-using code) finds your queue.py before the standard library module. To confirm, print queue.__file__ and check that it points into your project, and print sys.path[0] to see the script directory. The fix is to rename your file (for example to task_queue.py), delete the stale __pycache__/queue*.pyc, and run again. Checking a name against sys.stdlib_module_names before creating a file avoids the problem.
Exercise
A module contains data = open("input.csv").read() at the top level. List two problems this causes, and show how to restructure it so importing the module has no effect.
Show answer
Problems: importing the module fails with FileNotFoundError if the file is missing or the working directory differs, and the file is read (and its handle used) every time the module is first imported, including in tests and tooling. Also the content is frozen in sys.modules for the whole process. Restructure by wrapping the work in a function: def load_data(path="input.csv"): with open(path) as f: return f.read(). Callers decide when to read, and can pass a different path in tests.