Basic importing question

Christian Heimes lists at cheimes.de
Wed Aug 20 07:46:37 EDT 2008


Hussein B wrote:
> Thank you both for your kind help and patience :)
> Built-in modules are compiled but even if they are so, when importing
> them (sys for example), Python will run their code in order to create
> bindings and objects, right?
> I'm learning Python and I want to learn it well, so that I'm asking a
> lot :)

Yes, Python has to compile and execute the module before it can be used. 
But this happens only *once* for every module during the life time of a 
Python process. In Python modules are singletons. The second import just 
retrieves the module for an internal cache (sys.modules) and stores it 
in the current namespace.

The answer to your question "If all the modules files are importing sys 
module, how many times the sys module will be compiled and executed?" is 
  once.

By the way sys is a very special module, which is *always* loaded and 
initialized durings startup. The sys module is not only a builtin module 
  (embeded into the Python executable / library). It's also part of the 
heart of Python and treated more special than any other module.

Christian




More information about the Python-list mailing list