orphan:
Causes of ImportError¶
- turn into ImportError subclasses, __cause__
Other Exceptions During Import¶
- SyntaxError
- IOError?
Common Import-related Problems¶
circular imports¶
module behaves differently when run as script¶
- don’t run non-scripts as scripts; import in a test script
imports in scripts and at REPL behave differently than expected¶
- minimize the amount of code in scripts
- relative imports behave a little differently in scripts
reloading modules¶
no .pyc created¶
- .pyc for <name> is created only for “import <name>”
- caching was turned off
- file is actually in __pycache__ directory
- python run with -O flag (optimized) so .pyc files created
undesired import conflicts with files in CWD¶
By default the current working directory is first on sys.path. If this is causing trouble, you can move it to the back of the line:
try: sys.path.remove('')
except ValueError: pass
else: sys.path.append('')
Alternatively, you could remove it entirely (don’t append it back on).
stale code¶
orphaned pyc file getting used¶
If a directory has a pyc file but no matching py file, the module will be loaded from the pyc file directly. Starting with PEP 3147 (Python 3.2), orphaned pyc files in the __pycache__ directory are NOT loaded. The behavior use of pyc files otherwise stays the same. Either way, if you don’t want the module to be loaded from an orphaned pyc file, delete that file. Also see this tracker ticket <orphaned_pyc_files>.
alternate sys.modules ignored¶
Sometimes it can be helpful to replace sys.modules with a custom dictionary. However, in CPython, this does not affect the underlying dictionary that was originally bound to sys.modules. That is a separate part of the interpreter state. The behavior of the default _builtin___import__(), implemented in Python/import.c, actually uses this underlying dictionary through PyImport_GetModuleDict(), rather than explicitly pulling sys.modules. So your fancy-pantsy sys.modules is never used.
Luckily, importlib does explicitly use sys.modules, so if you switch over to that it should work just fine. This will be an even smaller issue once importlib’s __import__ because the default builtin.
import loads some other mysterious module¶
If you have a module file in your sys.path, and you try to import it, sometimes the import will succeed but the module will be the wrong one. This can be both mysterious and perplexing.
The first thing to do is to see if you have a package (directory with a __init__.py) by the same name in the same place as that module file. If so, Python will import from the package instead of the module. To verify this, import the module: “import <name>” and then check the module in sys.modules: “import sys; print(sys.modules[‘<name>’])”. You should see it pointing to the __init__.py of the package instead of the module file you were expecting.