Unexpected import behavior
M.-A. Lemburg
mal at lemburg.com
Fri Jun 22 16:03:01 EDT 2001
Chuck Esterbrook wrote:
>
> Under the old mxDateTime, I had:
>
> import DateTime
> from DateTime import now, RelativeDateTime
>
> The new one is inside a package. No problem, I thought:
>
> from mx import DateTime
> from DateTime import now, RelativeDateTime
You have to rewrite this as:
from mx.DateTime import now, RelativeDateTime
> But that gives me this:
>
> Traceback (most recent call last):
> File "./DailyLinks21.py", line 24, in ?
> from DateTime import now, RelativeDateTime
> ImportError: No module named DateTime
>
> Obviously there is a DateTime variable by the time we get to the second
> statement and it points to a module. I printed the repr() and type() to
> make sure.
>
> An examination of sys.modules.keys() shows, however, that there is no
> 'DateTime', but only 'mx' and 'mx.DateTime'.
Python will (almost) always register the modules under their
absolute dotted path names.
> Using a Python package containing a package containing a module, I created
> the same problem. I then created it with Python 2.0 and 1.5.2.
>
> The behavior seems rather non-intuitive (although easily fixed in this
> case). I guess the explanation from those familiar with Python internals
> will be something along these lines:
> - import uses sys.modules.keys() not the symbols where it is located
Right.
> - "from pkg import module" does not "unqualify" the module for future
> imports even in the module where this statement appears
Right again ;-) It does however make the "from" name available,
e.g.
import mx.DateTime
from mx.DateTime import now
will work. You can also do:
from mx import DateTime
from mx.DateTime import now
> So at this point, I'm wondering if you think this behavior is
> intuitive/"correct" and whether or not it would make any sense to change
> it. For example, could import look at local symbols before sys.modules?
I don't think it would be a good idea to start mixing scopes
here. Using the absolute package names gives you a very good
idea of where the different APIs in your namespace are
coming from.
Also, I am not sure whether the import hook has access to the
current scope.
--
Marc-Andre Lemburg
CEO eGenix.com Software GmbH
______________________________________________________________________
Company & Consulting: http://www.egenix.com/
Python Software: http://www.lemburg.com/python/
More information about the Python-list
mailing list