[Python-Dev] PEP 451 update

Nick Coghlan ncoghlan at gmail.com
Sun Oct 27 21:59:24 CET 2013


On 28 Oct 2013 02:37, "PJ Eby" <pje at telecommunity.com> wrote:
>
> On Sun, Oct 27, 2013 at 1:03 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> > Now, regarding the signature of exec_module(): I'm back to believing
> > that loaders should receive a clear indication that a reload is taking
> > place. Legacy loaders have to figure that out for themselves (by
> > seeing that the module already exists in sys.modules), but we can do
> > better for the new API by making the exec_module signature look like:
> >
> >     def exec_module(self, module, previous_spec=None):
> >         # module is as per the current PEP 451 text
> >         # previous_spec would be set *only* in the reload() case
> >         # loaders that don't care still need to accept it, but can
> > just ignore it
>
> Just to be clear, this means that a lazy import implementation that
> creates a module object without a __spec__ in the first place will
> look like an initial import?  Or will that crash importlib because of
> a missing __spec__ attribute?
>
> That is, is reload()'s contract adding a new prerequisite for the
> object passed to it?
>
> (The specific use case is creating a ModuleType subclass instance for
> lazy importing upon attribute access.  Pre-importlib, all that was
> needed was a working __name__ attribute on the module.)

For custom loaders, that's part of the contract for create_module() (since
you'll get an ordinary module otherwise), and so long as *setting* the
special module attributes doesn't cause the module to be imported during
the initial load operation, attribute access based lazy loading will work
fine (and you don't even have to set __name__, since the import machinery
will take care of that).

For module level lazy loading that injects a partially initialised module
object into sys.modules rather than using a custom loader or setting a
__spec__ attribute, yes, the exec_module invocation on reloading would
always look like a fresh load operation (aside from the fact that the
custom instance would already be in sys.modules from the first load
operation). It *will* still work, though (at least, it won't break any
worse than such code does today, since injecting a replacement into
sys.modules really isn't reload friendly in the first place).

Cheers,
Nick.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20131028/f7773f0c/attachment.html>


More information about the Python-Dev mailing list