PEP 690: Add a simple example of the behavior (#2577)

This commit is contained in:
Carl Meyer 2022-05-06 18:09:50 -06:00 committed by GitHub
parent 3f4a6f9af6
commit 153cd9eb8b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 35 additions and 0 deletions

View File

@ -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
-------------