import keyword behaviour - performance impact if used multiple times?

Nick Coghlan ncoghlan at
Sat Nov 27 14:10:49 CET 2004

Andrew James wrote:
> Hi,
> I've been looking around on Google for the answer to this question, and
> it's beginning to really bug me. I'm making some design decisions for
> some code I'm writing, and I'm wondering whether (Good Design Decisions
> apart), there's a performance impact in importing the same module in two
> different files. For example, with the following:
> -----------
> import psycopg
> class A:
>   ....
> import psycopg
> class B:
>    a = A()
>    ....
> If I run fileB, will this import the psycopg twice, or once only?

I'm guessing should read:
   import psycopg
   import A

Anyway, when Python imports modules it stores a reference to them in 
sys.modules. Any attempts to import the module again are satisfied using the 
cached version already stored in sys.modules.

So, in your example, psycopg is imported once only, and both fileA and fileB 
would be referring to the same version of psycopg.

 > Is
 > this something to do with system modules being singletons?

They aren't singletons in the GoF design pattern sense. However, Python's import 
machinery operates in such a way that it takes effort to get multiple version of 
the same module into memory at the same time (it *can* be done, but you have to 
work at it).


More information about the Python-list mailing list