Graham Dumpleton: Lazy imports... Note

Graham Dumpleton: Lazy imports using wrapt

PEP 810 introduces explicit syntax for lazy module imports in Python. Previously, packages offered similar functionality but lacked dedicated language support. The wrapt library's new lazy object proxy feature can implement lazy imports easily. Wrapt's core purpose is monkey patching, which involves transparent object proxies. These proxies intercept access to target objects, enabling specific actions. A lazy object proxy takes a function that creates the target object upon first access rather than the object itself. This allows for lazy module importing, as demonstrated with an example using wrapt.LazyObjectProxy and __import__. Unlike some methods that alter sys.modules upfront with a fake module, this approach avoids global changes. The impact of the wrapt example is confined to the scope where the lazy import is made, aligning with PEP 810's goal of localized effects. However, it requires a different syntax than standard import statements. PEP 810 aims to avoid fake module objects in the scope, ensuring the reference becomes the actual module upon first use. The wrapt example maintains a proxy object, with potential future enhancements to replace it with the actual module.