From 153cd9eb8bba551eafe242b79324ee81d736fa7c Mon Sep 17 00:00:00 2001 From: Carl Meyer Date: Fri, 6 May 2022 18:09:50 -0600 Subject: [PATCH] PEP 690: Add a simple example of the behavior (#2577) --- pep-0690.rst | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/pep-0690.rst b/pep-0690.rst index d95cccdfc..6e638d9ec 100644 --- a/pep-0690.rst +++ b/pep-0690.rst @@ -140,6 +140,41 @@ Dynamic imports using ``__import__()`` or ``importlib.import_module()`` are also never lazy. +Example +------- + +Say we have a module ``spam.py``:: + + # simulate some work + import time + time.sleep(10) + print("spam loaded") + +And a module ``eggs.py`` which imports it:: + + import spam + print("imports done") + +If we run ``python -L eggs.py``, the ``spam`` module will never be imported +(because it is never referenced after the import), ``"spam loaded"`` will never +be printed, and there will be no 10 second delay. + +But if ``eggs.py`` simply references the name ``spam`` after importing it, that +will be enough to trigger the import of ``spam.py``:: + + import spam + print("imports done") + spam + +Now if we run ``python eggs.py``, we will see the output ``"imports done"`` +printed first, then a 10 second delay, and then ``"spam loaded"`` printed after +that. + +Of course, in real use cases (especially with lazy imports), it's not +recommended to rely on import side effects like this to trigger real work. This +example is just to clarify the behavior of lazy imports. + + Debuggability -------------