I thought I understood how import worked...

Laszlo Nagy gandalf at shopzeus.com
Tue Aug 7 10:14:15 EDT 2012


On 2012-08-07 15:55, Ben Finney wrote:
> Roy Smith <roy at panix.com> writes:
>
>> So, it appears that you *can* import a module twice, if you refer to
>> it by different names! This is surprising.
> The tutorial is misleading on this. It it says plainly:
>
>      A module can contain executable statements as well as function
>      definitions. […] They are executed only the *first* time the module
>      is imported somewhere.
>
>      <URL:http://docs.python.org/tutorial/modules.html>
>
> but it doesn't make clear that a module can exist in the ‘sys.modules’
> list multiple times under different names.
sys.modules is a dict. But yes, there can be multiple "instances" of the 
same module loaded.

What I do with bigger projects is that I always use absolute module 
names. For example, when I develop a project called "project1" that has 
several sub packages, then I always do these kinds of imports:

from project1.package1.subpackage2.submodule3 import  *
from project1.package1.subpackage2 import  submodule3
from project1.package1.subpackage2.submodule3 import  some_class

Even from a source file that is inside project1.package1.subpackage2, I 
tend to import them the same way. This makes sure that every module is 
imported under the same package path.

You just need to make sure that the main project has a unique name 
(which is usually the case) and that it is on your sys path (which is 
usually the case, especially when the script is started in the project's 
directory).

The cost is that you have to type more. The benefit is that you can be 
sure that you are importing the thing that you want to import, and there 
will be no multiple imports for the same module.

Mabye somebody will give method that works even better.

For small projects without sub-packages, it is not a problem.

Best,

    Laszlo




More information about the Python-list mailing list