Python imports: eight ways you get the wrong file
The service restarted three times and the output was still one line. I had swapped json.dumps for json.dump, added indent=2, saved the file twice, and finally printed json.__file__ inside the running process. It pointed at json.py in the project directory: a 17-byte file I had created months earlier for a throwaway migration script.
That is the part of import nobody thinks about. A failed import raises. A successful import of the wrong file says nothing at all. It did run an import; the module just was not the one in your head.
I ran all eight cases below on this machine: Windows 11, CPython 3.13.14 (MSC v.1944, 64-bit), measured on 2026-11-13. Standard library only, no third-party packages installed. Every output block is pasted verbatim. There are no affiliate links in this article and no commission links of any kind.
TL;DR: six of ten paths exit with code 0
TL;DR: imports fail loudly only when nothing is found. Ten reproducible paths, six of which end with exit code 0: they never turn CI red and never stop the service from booting. They just make one singleton into two, make isinstance quietly return False, and keep running code you already replaced. Three commands locate the real file: module.__file__, importlib.util.find_spec(name).origin, and python -X importtime.
| Case | Trigger | Failure shape | Exit code |
|---|---|---|---|
| Name shadowing | json.py sits next to your script | AttributeError plus a rename hint | 1 |
| Empty path entry | -c start plus a later os.chdir() | Silently imports the other file | 0 |
| Stale bytecode | Same byte size, same integer second | Old code runs, no warning | 0 |
| Top-level cycle | Two modules import each other with from | ImportError that never mentions a cycle | 1 |
Same cycle, plain import | No attribute access at import time | Half-built module object | 0 |
| Run a file inside a package | python pkg/mod.py | ModuleNotFoundError | 1 |
Same file via -m | python -m pkg.mod | Two module objects | 0 |
| Namespace package | Directory without __init__.py | TypeError on __file__ | 1 |
| Two spellings | PYTHONCASEOK set | Two objects, separate state | 0 |
reload() | An earlier from m import f | The old function keeps running | 0 |
The table is the whole argument: exit code is not the criterion.
First, the order of an import
Four steps, and any of them can be hijacked by a file you forgot about.
One: the cache. The documentation states it plainly: "The first place checked during import search is sys.modules", and "During import, the module name is looked up in sys.modules and if present, the associated value is the module satisfying the import, and the process completes." The second half matters: a hit ends the search, and no further lookup happens.
Two: sys.meta_path, which by default holds three finders (built-in, frozen, path-based). The third one is where trouble lives. It walks sys.path in order and asks each entry whether it has the module.
Three: register, then execute. "The module will exist in sys.modules before the loader executes the module code." That sentence explains two later sections: a circular import can hand you a half-built module, and a module importing itself does not recurse forever.
The critical detail is "walks sys.path in order". Here is the list on this machine, nine entries, four of them shown:
0 ''
1 D:\openclaw-blog\tmp\implab-1113\pathorder
2 ...\python313.zip
3 ...\DLLs
4 ...\Lib
6 C:\Users\xuany\AppData\Roaming\Python\Python313\site-packages
8 ...\Lib\site-packages
The standard library directory Lib is index 4. User site-packages is 6, system site-packages is 8. So your own directory outranks the standard library, while installed packages rank below it. One rule, two very different outcomes, and that is the entire cause of the first trap.
Trap one: a same-named file next to your script beats the standard library
Drop a json.py containing one line, MARK = 'local json', next to this main.py:
import json
print('file =', json.__file__)
print('has dumps =', hasattr(json, 'dumps'))
print(json.dumps({'a': 1}))
The run:
file = D:\openclaw-blog\tmp\implab-1113\lab1\e1\json.py
has dumps = False
AttributeError: module 'json' has no attribute 'dumps' (consider renaming
'D:\openclaw-blog\tmp\implab-1113\lab1\e1\json.py' since it has the same name
as the standard library module named 'json' and prevents importing that
standard library module)
Two signals in three lines. First, json.__file__ already points at the local file, so the import succeeded. Second, 3.13 appended a rename hint that says outright this file "prevents importing that standard library module". Older versions gave you only the bare AttributeError, which reads like the standard library changed its API overnight.
PYTHONPATH behaves the same way. Put the same json.py in a directory, start with PYTHONPATH=., and json.__file__ still points at the local file, because the PYTHONPATH entry lands at index 1, still ahead of Lib at index 4.
site-packages is the opposite case: it ranks after the standard library, so a package named json installed there cannot shadow it. I inferred that one from the measured sys.path order rather than by installing a fake package; I am flagging the difference so the claim is not read as something I ran.
The check costs nothing: run python -c "import json; print(json.__file__)" from the project root and look for your own directory in the output.
Trap two: entry zero of sys.path has three different identities
The same import helper resolves differently depending on how the interpreter was started. Measured:
| How it starts | sys.path[0] |
|---|---|
python main.py | absolute path of the script's directory |
python -c "..." | the empty string '' |
python -m probe | absolute path of the current directory |
The documentation covers all three: for -c, "the current directory will be added to the start of sys.path"; for a script, "the directory containing that file is added to the start of sys.path, and the file is executed as the __main__ module".
The difference is not what entry zero holds, but when it is resolved. An absolute path is frozen at startup. The empty string is a placeholder, interpreted against the current directory at each import. So os.chdir() changes what later imports resolve to, and the two start modes diverge.
I built a/ and b/, each with a helper.py (WHERE = 'a' and WHERE = 'b'), started with -c, imported once, changed directory, dropped the sys.modules entry, and imported again:
cwd-run first a
cwd-run second b
One process, one statement, two different modules. Running the identical sequence as a script keeps returning a, because entry zero is the absolute path of a and does not follow the working directory.
In real projects this looks like: CI runs cd build && python ../scripts/gen.py while your IDE runs the same file directly. Entry zero differs, and so does the winner among same-named modules. Since 3.11 there is a switch that removes the ambiguity: python -P does not prepend a potentially unsafe path. Rerunning inside the directory that holds the shadowing json.py with -P, json.__file__ went back to the standard library and has dumps came back True.
Trap three: .pyc validity checks integer seconds and byte size, nothing else
This is the most counter-intuitive one, because it never reads the file it is validating.
Default bytecode caches carry no source hash. They carry two numbers: the source modification time truncated to whole seconds, and the source size in bytes. The loader contains source_mtime = int(st['mtime']), and the validation compares _unpack_uint32(data[8:12]) against source_mtime, then _unpack_uint32(data[12:16]) against source_size.
That leaves a narrow but entirely real hole: same byte count, and the edit lands inside the same integer second, and the stale cache stays valid.
I reproduced it deliberately. Write VALUE = 'first', import once to build the cache, then rewrite as VALUE = 'FIRST' (a case swap, still 17 bytes), then reset the modification time to the original second with os.utime. The file on disk now says FIRST. Import again:
file on disk now: VALUE = 'FIRST' | size 17
run2: first
It prints first. Exit code 0, no warning. Moving the modification time forward five seconds makes the same import print FIRST, which pins the cause on that one second.
The diagnostic output deserves more attention than the bug. python -v does not say it read a cache; it says:
# ...\__pycache__\greet.cpython-313.pyc matches ...\greet.py
# code object from '...\__pycache__\greet.cpython-313.pyc'
One matches and the source is skipped. I unpacked the cache header to confirm the two numbers: source_mtime = 1794521655, source_size = 17.
Hash-based caches cannot be fooled this way. Compile once with py_compile.compile(..., invalidation_mode=PycInvalidationMode.CHECKED_HASH), apply the identical same-size, same-second rewrite, and the import picks up the new value. Of the two invalidation modes, only 50% falls to this trick, and it is the timestamp one.
Where it bites in practice: codegen that writes a module and imports it immediately (template rendering, DTO generation, migration scaffolds); image builds or tar extraction that flatten modification times; file sync that preserves old timestamps across machines. This host happens to set PYTHONDONTWRITEBYTECODE=1, which is why my first attempt produced no __pycache__ at all and the trap was invisible until I unset it. Production containers rarely set it.
Trap four: two circular-import messages, and the top-level one never says "circular"
Same bug, different wording depending on whether the modules are top-level files or inside a package. One of those wordings never mentions the cycle.
Two top-level files, alpha.py doing from beta import BEE and beta.py doing from alpha import VALUE, with VALUE assigned after the import line:
ImportError: cannot import name 'VALUE' from 'alpha' (consider renaming
'...\alpha.py' if it has the same name as a library you intended to import)
The advice is to rename the file, on the suspicion that you collided with a library. It says nothing about a circular import. Follow that advice and you get the same error under a new filename.
Put the same cycle inside a package and the message changes completely:
ImportError: cannot import name 'A' from partially initialized module 'pkg.a'
(most likely due to a circular import) (...\pkg\a.py)
partially initialized module plus most likely due to a circular import is the sentence that leads to answers. So "why can everyone find this error but me" is sometimes not a search-skill problem; it is a different message.
More expensive than either error is the silent variant. Change from alpha import VALUE to import alpha, then have delta.py do import gamma and read an attribute:
delta sees []
ok
delta sees [] shows it received a shell with no attributes, because gamma had executed only its first line. Exit code 0. The failure surfaces later, somewhere else, as AttributeError: module 'a3' has no attribute 'A', with no trace of the cycle in the stack.
One detail saves hours: order decides. Move A = 1 above from .b import B and the same cycle works, printing b got A = 1. So do not only ask who imports whom; ask which line assigns the name being imported.
Trap five: __main__ is a second copy of the module
Run a file inside a package two ways and you get two behaviors, the second one quieter.
pkg/state.py builds a module-level dict REGISTRY and ends with if __name__ == '__main__' importing pkg.state itself. Run it directly:
python pkg/state.py
ModuleNotFoundError: No module named 'pkg'
Same cause as trap two: entry zero became the pkg/ directory, the repository root is not on the path, and the package name cannot resolve.
python -m pkg.state works, but the module body runs twice:
body runs, __name__ = __main__
body runs, __name__ = pkg.state
two module objects: True
Two module objects, two dictionaries, two ids. The __main__ copy and the pkg.state copy do not know each other; anything written into one is invisible to the other. In production this becomes half a registry, a web application instantiated twice, signal handlers registered twice, a singleton connection pool that is now two pools.
The fix is boring: keep the entry file to a single call into main(), create no module-level state there, or add pkg/__main__.py and put state in modules that get imported normally. The same "did the code I think ran actually run" question, measured against test doubles, is what the mutation-style unittest.mock experiments are about.
Trap six: no __init__.py still imports, and __file__ is None
Since PEP 420 a directory without __init__.py is still a package, a namespace package. The documentation is direct: "With namespace packages, there is no parent/__init__.py file." Its __path__ is not an ordinary list either: "They instead use a custom iterable type which will automatically perform a new search for package portions on the next import attempt within that package if the path of their parent package (or sys.path for a top level package) changes."
I built a tree with only ns/sub/leaf.py and no __init__.py anywhere. import ns.sub.leaf succeeded and leaf.V returned 1. Then:
ns.__file__ = None
ns.__path__ = _NamespacePath ['D:\openclaw-blog\tmp\implab-1113\lab2\e5\ns']
TypeError: argument should be a str or an os.PathLike object where __fspath__
returns a str, not 'NoneType'
__file__ is None, so Path(ns.__file__).parent raises TypeError. That line appears in logging setup, resource loading and template path resolution in a great many projects, and the error names neither the variable nor the package.
So "should a package directory have an __init__.py" is a contract question, not a style question. If any code touches package.__file__, even to print a startup path, add one. To read data files inside a package, the right tool is importlib.resources, which resolves through __path__ and never touches __file__.
Trap seven: one file can be two module objects
Keys in sys.modules are exact strings. File systems may or may not be case-sensitive. Put those together and one file becomes two modules.
On Windows the default is actually case-sensitive: with Casemod.py on disk, import casemod raises ModuleNotFoundError: No module named 'casemod'. But the documentation keeps an escape hatch: "If this is set, Python ignores case in import statements. This only works on Windows and macOS." With PYTHONCASEOK=1 and both spellings in one file:
same object = False
STATE = ['x'] []
isinstance across both = False
sys.modules keys = ['Casemod', 'casemod']
All four land: two module objects, two lists, isinstance returns False across the two class objects without raising, and sys.modules holds two keys pointing at the same file.
This is the hardest class of production bug to read: type checks pass, logic passes, and objects still fail isinstance; a registry singleton appears to work "sometimes". It belongs to the same family as two strings that look identical but never compare equal: the identity you see and the identity the interpreter uses are two different things. The fix is crude but effective: one naming convention, and no PYTHONCASEOK in CI. If you work on a case-insensitive file system (macOS defaults to one), this case is worth running yourself; I have no macOS machine, so that line is a reminder, not a result.
Trap eight: reload does not rebind names you already imported from the module
Hot-reload scripts reach for importlib.reload() first. It does less than most people assume.
Measured: module m has f() returning 'v1'. The main program does both from m import f and import m. At runtime the file is rewritten to return 'v2', then importlib.reload(m) runs:
before = v1
module.f() = v2
bound f() = v1
f is m.f = False
The reload did recompile and re-execute the module body, and m.f is the new function. But the name you bound earlier with from m import f still points at the old function object. The documentation lists it among the caveats: "Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired."
A second sentence in the same section is worse: "If the new version of a module does not define a name that was defined by the old version, the old definition remains." Deleted functions do not disappear, because the module dictionary is retained and then updated.
Worth pinning down while we are here, since it saves time on NameErrors:
| Statement | Name bound |
|---|---|
import pkg.mod | only pkg; mod is unbound |
import pkg.mod as mm | only mm; not even pkg |
from pkg import mod | only mod |
After the first form, mod.VALUE raises NameError: name 'mod' is not defined while pkg.mod.VALUE works. That asymmetry ruins somebody's afternoon every year.
Troubleshooting: three commands that name the real file
First, print the source. One print(json.__file__) at the suspect point, or print(pkg.__path__) for a package, converts "I assume" into a path and settles most cases.
Second, inspect without importing. importlib.util.find_spec('json').origin returns the file that would be loaded without executing the module body. On this machine:
C:\Users\xuany\.workbuddy\binaries\python\versions\3.13.12\Lib\json\__init__.py
Third, read import timing. python -X importtime writes to stderr in three columns: self time, cumulative time, module name, in microseconds. The json line here:
import time: 987 | 18903 | json
987 microseconds for the module itself, 18,903 including dependencies. The useful signal is a module you never wrote appearing in the list, or a familiar name resolving from an unexpected path. Redirect stderr to a file and sort by name; it beats reading code.
One more, invisible until needed: python -v prints, line by line, which file each module came from and whether a cache matched. That is where the matches line in trap three came from. It is verbose; use it to pin down a single module.
If you only keep a checklist, keep these six:
- No files in the project root that share a name with stdlib modules (
json.py,types.py,random.py,logging.py,queue.pyare the usual suspects) - Run code inside packages as
python -m pkg.module, notpython pkg/module.py - Packages whose
__file__matters need an__init__.py - Codegen pipelines that import their own output should set
PYTHONDONTWRITEBYTECODE=1or use hash-based bytecode - For circular imports, move the import into a function rather than reordering assignments
- For hot reload, use
import m; m.f(), neverfrom m import fplusreload
What this article does not cover
I measured CPython 3.13.14 on Windows 11 only. Untested, and therefore not claimed: macOS and Linux behavior for case sensitivity and mtimes; how Docker layers flatten modification times and what a read-only file system does when the bytecode write fails; PyPy and freezer toolchains; zipimport and frozen modules; message differences across 3.8 through 3.12, since the rename hint and -P are both recent. The reload behavior in trap eight has been documented for a long time, but whether your framework wraps reload is something only your code can answer.
If you want the same "what the interpreter actually did, not what the code appears to say" angle applied to numbers, the rounding and Decimal cases cover the last digit of money.
FAQ
Q: Does deleting __pycache__ make this go away?
Only the cache layer. Shadowing, circular imports and the __main__ duplicate have nothing to do with bytecode, and the cache is rebuilt on the next import anyway. The reverse is a useful test: if deleting the cache fixes your "my change did not take effect" problem, you were almost certainly in trap three.
Q: If I install a package named json, does it shadow the standard library?
By the sys.path order measured here, no: site-packages ranks after the standard library. The dangerous entries are the script directory and PYTHONPATH, both of which rank ahead of it. The mechanism is lookup order, not the name.
Q: It works locally, why does the container raise ModuleNotFoundError?
Start with how the process is launched. python pkg/mod.py puts pkg/ into sys.path[0] and leaves the repository root off the path, and container working directories rarely match your laptop. Use python -m with a fixed working directory and this whole category disappears.
Q: Why is b undefined after import a.b?
Because import a.b binds only a. Write a.b.x, or from a import b, or import a.b as b. That is statement syntax, independent of whether the module exists.
👉 Join Xiaomi MiMo Platform: Leading AI model platform with cost-effective inference
👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation
📌 This article was AI-assisted generated and human-reviewed | TechPassive — An AI-driven content testing site focused on real tool reviews
🔗 Recommended Tools
These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:
As an Amazon Associate, I earn from qualifying purchases at no extra cost to you.