Cross-reference 'import' in a class hierarchy

Marcus Alanen marcus at infa.abo.fi
Wed Apr 9 06:16:03 EDT 2003


On Tue, 8 Apr 2003 14:08:04 -0400, Jp Calderone <exarkun at intarweb.us> wrote:
>  This line:
>
>    "from foobar import t2 as t1"
>
>  causes "foobar" to be imported, adding "foobar" to sys.modules, then
>causes "foobar.t2" to be imported, adding "foobar.t2" to sys.modules, then
>binds the local "t1" to that module object.
>
>  This line:
>
>    "import t2"
>
>  causes "t2" to be imported.  Before it is -actually- imported, sys.modules
>is checked for the string "t2" to see if the module has already been loaded. 
>If it has, that module object is returned, but if it hasn't (and as far as
>Python knows, it hasn't, only "foobar.t2" has been imported, and that is
>clearly a different module), "t2" is added to sys.modules and the local "t2"
>is bound to the new module object.

OK, this certainly explains very well "how" things happen. Thank you.

>  Hopefully you see now that there are two copies of A, because there are
>two copies of the module.

Yes. Although I find it non-intuitive; python could have determined
it's the same file by checking major/minor and inode fields of the
file (on unix).  Hmm.. perhaps this (or something similar) isn't
possible on all operating systems?

>> This leads (IMHO) to the fact that one _never_ should use "import X",
>> (witness isinstance(t1.A(), t2.A) returning 0...) everything should go via
>> PYTHONPATH. Which in turn means that you have to set PYTHONPATH for all
>> programs. ?
>  One could look at it that way.  One could look at it another way, too:
>don't mix imports in such a way that the same module may be referred to by
>more than one name.

I fail to see how this feature would help anybody. Where's the benefit
of being able to import the same module into two different names
with "import Y" and "from X import Y" statements, and _relying_ on them
being different copies? Brittle at best, and most likely error-prone.
I would understand it if a local "__import__" would create a separate
namespace.

Regards,
Marcus

-- 
Marcus Alanen
maalanen at abo.fi




More information about the Python-list mailing list