PEP 810: Explicit lazy imports

So I was less than clear in my reasoning here, but my understanding is that in the current model, when __lazy_modules__ is set, it will not lazily import in a context, but it also won’t be a syntax error, so:

__lazy_modules__ = ["foo", "bar"]

import foo # lazy

with blah():
    import bar  # eager

If we change it so that both of these are lazy, then I think that lazy import … should also be allowed in the with block as well, because otherwise I think people will think “well lazy importing isn’t allowed in context managers so obviously this is eager”.

If however we allow lazy imports in a context manager, you don’t need any hacks in Python 3.15 and no careful thought needs to be done about replacing __import__ with __lazy_import__, because it will just work out of the box once __lazy_import__ exists, and the hacks can all go into the backport.

3 Likes