Inspect a module origin using find_spec

importlib.util.find_spec() can expose a module's ModuleSpec without binding that module name in the current namespace. A spec includes an origin field: for source modules it is commonly a filename, while loaders without a file location can use another meaningful marker. This example looks up the standard-library sys module. In CPython, its expected origin is the exact string "built-in", so the code asserts that marker and prints the fully qualified spec name plus a deterministic Boolean result.

The concrete input is therefore "sys", not a pathname. The output does not disclose an installation directory and avoids treating origin as a universally usable filesystem path. That distinction matters: a module spec's origin describes the loader's loading location, and namespace packages may have None instead. Furthermore, module.__file__ and module.__spec__.origin are not kept synchronized if either changes at runtime. Inspect a returned spec for diagnostics or controlled routing, but do not assume that an origin alone proves provenance or that every Python implementation represents built-in modules identically.

ModuleSpec and importlib.util.find_spec() are available from Python 3.4. See the find_spec documentation and the ModuleSpec origin documentation.

import importlib.util

spec = importlib.util.find_spec("sys")

assert spec is not None
assert spec.origin == "built-in"
print(f"name: {spec.name}")
print(f"origin-is-built-in: {spec.origin == 'built-in'}")
name: sys
origin-is-built-in: True

AI-assistance disclosure: AI helped draft this explanation and example.

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic