Why doesn't `from pkg import mod' work after `del pkg.mod'?

ryles rylesny at gmail.com
Sat Jul 25 21:11:23 CEST 2009


On Jul 25, 8:57 am, Piet van Oostrum <p... at cs.uu.nl> wrote:
> >>>>> ryles <ryle... at gmail.com> (r) wrote:
> >r> According tohttp://www.python.org/doc/essays/packages.html:
> >r> "The import statement first tests whether the item is defined in the
> >r> package; if not, it assumes it is a module and attempts to load it."
> >r> However, I've noticed that once a module is imported using the
> >r> `from pkg import mod' syntax, if its name is deleted from the
> >r> package namespace then subsequent imports with `from' will fail.
>
> This is incorrectly stated. Also on the initial import it will fail, not
> just on subsequent imports.
>
> piet$ python
> Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
> [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.>>> from pkg import _impl
>
> _impl # this is from a print statement in _impl to show that it did import
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ImportError: cannot import name _impl
>

Well, since __init__.py is executed first, I would regard it as
causing the initial (successful) import, and yours being the
subsequent one, so that the "initial" import does not fail, the
subsequent one does. Wording aside, though, I think we are on the same
page here.

>
> According to the documentation
> <http://docs.python.org/library/functions.html#__import__> the statement
> from pkg import _impl
>
> _temp = __import__('pkg', globals(), locals(), ['_impl'], -1)
> _impl = _temp._impl
>
> This fails because _temp (the imported module) doesn't have a binding
> for _impl because you deleted it.

But supposing we hadn't deleted it, and __init__.py didn't import
_impl, there would still be no binding. Yet the importer would still
import and make the module available (presumably it "knows" to do this
since it was not already in sys.modules). The question really is that
since in our example pkg._impl is still in sys.modules, why won't the
importer add it to the pkg namespace again as it previous had? I would
imagine this is either by design, or is a case that was never
considered.

> for _impl because you deleted it. By the way, if you have a `normal'
> package that doesn't do anything with the name _impl, after the import
> the pkg module namespace will have got a binding for _impl although it is not
> in your code. It will have been put there by the import code.

Yes, this was noted further down in the original post with an example.



More information about the Python-list mailing list