Eric Snow added the comment:

Regarding this:

>>> def f():
...     import html.entities
...     del sys.modules['html']
...
>>> f()
>>> import html.entities
>>> html.entities
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'entities'

This is due to the fact that the code to add the submodule to the package's 
namespace is associated with the import of the submodule, not the parent (aka, 
package).  So the import after calling f() happily bypasses all that since the 
submodule already exists in sys.modules.

skip loading the module: 

http://hg.python.org/cpython/file/default/Lib/importlib/_bootstrap.py#l1612

bind the submodule to the parent:

http://hg.python.org/cpython/file/default/Lib/importlib/_bootstrap.py#l1568

I wouldn't necessarily say the import machinery is acting weird.  Directly 
messing with sys.modules, particularly for submodules, isn't something the rest 
of the import code explicitly accommodates (outside of loaders).  In this case 
the code doing the removing needs to make sure submodules are removed too.

If anybody thinks we should support this sort of interaction with sys.modules 
then we could address it in another issue.  Outside of testing, what are the 
use cases for removing modules from sys.modules?  Regardless, a solution might 
be as simple as moving the parent-binding code in _find_and_load_unlocked() to 
_gcd_import().

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue18706>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to