How `modshim` works: AST Rewriting and Virtual Modules
mainCore Mechanism
modshim extends Python's import system by installing a custom ModShimFinder into sys.meta_path. It creates virtual merged modules by performing AST (Abstract Syntax Tree) rewriting on the source code during load time.
Key Concepts
- Mapping:
shim()maps three names:lower(original),upper(enhancement), andmount(the new combined entry point). - AST Rewriting:
modshimtransformsimport Xandfrom X import Ystatements to point to themountpoint. It also rewrites attribute access (e.g.,urllib.response) to ensure consistency. - Working Module: To prevent circular references when an enhancement subclasses an original component,
modshimcreates a temporary_working_<module>to hold the original namespace. - Isolation: Unlike monkey-patching, the original module is never modified. The enhancements only exist under the
mountpoint, preventing global namespace pollution.