
When Python executes import widget, it first checks sys.modules. If widget is already there, Python reuses that module; it does not search the filesystem again. Otherwise, Python asks the finders in sys.meta_path whether they can locate it. The standard PathFinder handles imports resolved through the import path.
For a top-level module, PathFinder searches the entries in sys.path in order. An entry might name a directory, a zip archive, or another location supported by an installed path hook. The first finder that reports a match supplies a module specification, which Python uses to create and load the module. An earlier matching name therefore takes precedence over a later one.
import sys print(sys.path)
For a module inside a package, Python searches the package’s __path__, rather than searching sys.path again. For example, resolving tools.parser first locates tools; then Python searches the locations recorded in tools.__path__ for parser. A package can have multiple search locations, as with a namespace package.
You can inspect what the standard path-based finder would locate without importing the target module:
import importlib.machinery
spec = importlib.machinery.PathFinder.find_spec("widget", None)
print(spec.origin if spec is not None else "not found")
The second argument is the search path: None means use sys.path for a top-level name. For a submodule, pass the parent package’s path instead:
import importlib.machinery
import tools
spec = importlib.machinery.PathFinder.find_spec(
"parser",
tools.__path__,
)
print(spec.origin if spec is not None else "not found")
Roku TV Replacement Remote Control (Official Manufacturer Product) | Simple Setup & Pre-Set App Shortcuts - Compatible with RokuTV & Brand Partner TV Models Only (Not Roku Players)
(as of November 15, 2026 02:18 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)What sys.path_importer_cache stores
sys.path_importer_cache is a dictionary used by PathFinder to remember which path-entry finder is associated with each entry it examines. Its keys are path-entry strings, such as directory names or zip-file paths; its values are finder objects returned by the path hooks in sys.path_hooks.
import sys
for entry, finder in sys.path_importer_cache.items():
print(repr(entry), "->", repr(finder))
A cached finder is not a module, a module specification, or a record of every module found in that location. It is the object that knows how to search that particular path entry. When Python looks for another module in the same location, it can reuse the finder instead of asking the path hooks to construct one again.
A value of None means that no path hook accepted the entry. Python caches that result too, avoiding repeated attempts to find a suitable finder for the same path entry.
import sys
entry = sys.path[0]
finder = sys.path_importer_cache.get(entry, "not cached")
print("entry:", repr(entry))
print("cached value:", repr(finder))
The dictionary is an implementation detail of the path-based import machinery, so its contents can change as imports search different entries. In particular, inspecting it does not tell you whether a specific module is already loaded; that information is in sys.modules.
When cached finders become stale
A cached finder can become stale when the location it searches changes after the finder has been created. For a directory, that may mean a module file has been added, removed, or replaced. The finder associated with a zip archive can likewise outlive changes to that archive.
The standard FileFinder caches information about directory contents. It checks directory metadata to decide when that information needs refreshing, but filesystem timestamp resolution can make a change temporarily invisible. In particular, creating a module immediately after a failed import can produce a second failed import even though the new file exists.
import importlib
import importlib.util
import pathlib
import sys
import tempfile
with tempfile.TemporaryDirectory() as directory:
sys.path.insert(0, directory)
try:
try:
importlib.import_module("late_module")
except ModuleNotFoundError:
pass
pathlib.Path(directory, "late_module.py").write_text(
"value = 42n"
)
importlib.invalidate_caches()
module = importlib.import_module("late_module")
print(module.value)
finally:
sys.path.remove(directory)
sys.modules.pop("late_module", None)
Staleness is not limited to filesystem finders. A custom finder may cache its own view of a remote registry, database, or generated module set. If that underlying data changes, the finder’s cached view can remain out of date until the finder refreshes it. Calling importlib.invalidate_caches() asks finders on sys.meta_path that provide an invalidate_caches method to discard such state.
A path entry can also retain a cached finder after the environment that made it meaningful has changed. For example, replacing a directory with a different filesystem object at the same path string does not necessarily construct a new finder. The cache records the association between the path-entry string and its finder; it does not guarantee that the finder’s assumptions about the location remain valid.
Invalidating entries after changing sys.path
When you add or change an entry in sys.path, call importlib.invalidate_caches() if a previous search might have cached information about that entry. The function asks meta-path finders that support cache invalidation to refresh their state. For the standard path-based finder, this includes invalidating cached path-entry finders and removing cached None entries, which represent path entries no hook previously accepted.
import importlib import sys sys.path.insert(0, "/opt/my_modules") importlib.invalidate_caches()
This matters when the path string was already searched before it was added to sys.path. For example, a failed import might have caused Python to cache None for that string. After a suitable path hook becomes available, or the entry becomes usable, invalidation lets Python try the hooks again rather than reusing that negative result.
Changing the order of existing entries in sys.path does not itself require rebuilding their finders: the path-based finder consults the current order when searching. But a module already present in sys.modules will still be reused, regardless of the new order. To test a different location for an already imported module, remove that module from sys.modules as well.
import importlib
import sys
sys.path.insert(0, "/opt/alternate_modules")
importlib.invalidate_caches()
sys.modules.pop("widget", None)
widget = importlib.import_module("widget")
print(widget.__file__)
Invalidating caches does not remove finder objects for every entry or unload modules. If you need Python to run the path hooks again for one specific entry, remove that entry’s cache record explicitly. Use the same path string that appears in sys.path_importer_cache; cache keys are path-entry strings, not normalized filesystem identities.
import sys entry = "/opt/my_modules" sys.path_importer_cache.pop(entry, None)
Removing a finder this way forces the next search of that entry to consult sys.path_hooks again. It does not remove modules previously loaded from the entry, and it does not refresh other finders. For changes to directory contents or finder-managed state, use importlib.invalidate_caches(); for a deliberate re-evaluation of one path entry, remove its specific cache record.
Testing imports with a clean importer cache
A test that changes a path entry should control two separate caches. Remove the target from sys.modules so Python does not reuse an already loaded module, and remove the path entry from sys.path_importer_cache so the next search asks sys.path_hooks for a finder again. Use the exact path-entry string inserted into sys.path.
import importlib
import pathlib
import sys
import tempfile
module_name = "test_plugin"
with tempfile.TemporaryDirectory() as directory:
module_path = pathlib.Path(directory, module_name + ".py")
module_path.write_text("value = 'from temporary directory'n")
sys.path.insert(0, directory)
sys.modules.pop(module_name, None)
sys.path_importer_cache.pop(directory, None)
importlib.invalidate_caches()
try:
module = importlib.import_module(module_name)
assert module.value == "from temporary directory"
assert pathlib.Path(module.__file__).parent == pathlib.Path(directory)
finally:
sys.modules.pop(module_name, None)
sys.path.remove(directory)
sys.path_importer_cache.pop(directory, None)
Removing the importer-cache entry is useful when the test needs to verify path-hook behavior, such as whether a custom hook accepts an entry. For an ordinary test that only creates a new module in a directory already on the path, importlib.invalidate_caches() is usually sufficient to refresh finder state; it does not, however, remove an existing module from sys.modules.
A test should avoid clearing all of sys.path_importer_cache unless it specifically needs to exercise every path hook. Other entries may belong to the test runner or environment, and discarding their finders can make import behavior slower or affect unrelated tests. Clear only the relevant entry, and restore any modified path or module state even when an assertion fails.
