[Python-Dev] cpython: Introduce importlib.util.ModuleManager which is a context manager to

Brett Cannon brett at python.org
Wed May 29 18:55:01 CEST 2013

On Wed, May 29, 2013 at 12:49 PM, R. David Murray <rdmurray at bitdance.com> wrote:
> On Wed, 29 May 2013 12:25:45 -0400, Brett Cannon <brett at python.org> wrote:
>> In case you want to suggest a name, the context manager returns the
>> module that should be initialized/loaded. So typical usage will be::
>>   class Loader:
>>     def load_module(self, fullname):
>>       with importlib.util.module_to_init(fullname) as module:
>>         # Load/initialize the module
>>         return module
>> Basically the manager either gets the module from sys.modules if it is
>> already there (a reload) or creates a new module and sticks it into
>> sys.modules so other imports will grab the right module object. If
>> there is an exception and the module was new, it deletes it from
>> sys.modules to prevent stale modules from sticking around.
> So it is a context manager to handle the exception?

It's to choose the right module (sys.modules or new) and if the module
is new and there is an exception to delete it from sys.modules (other
small details like setting __initializing__ but that's not important).
So both __enter__ and __exit__ have logic.

>  Now I think I see
> where Nick is coming from.
> How about 'managed_initializiation'?  That seems closer to the 'closing'
> model, to me.  It isn't as clear about what it is returning, though,
> since you are passing it a name and getting back a module, whereas in
> the closing case you get back the same object you send in.


> Perhaps 'managed_module'?

managed_module is better than managed_initialization.

More information about the Python-Dev mailing list