[Tutor] What does import really do?
rabidpoobear at gmail.com
Tue Aug 15 04:52:19 CEST 2006
jim stockford wrote:
> For example,
> import os
> import sys
> My take is that one uses the import keyword in a
> The Python interpreter reads the program and
> generates machine code.
> The import keyword directs the Python interpreter
> to find some library (which is not necessarily named,
> certainly not necessarily named in the import
> statement), get some portion of machine code from
> the library, bind that machine code in current
> program's process space, and integrate the names
> of the imported machine code with the program's
> namespace (probably keeping the namespace of
> the imported code as a separate name domain).
I don't know when code is converted to machine code, but here's how I think
you say 'find some library ... not necessarily named in the import
I don't know what you mean by this.
If the user says 'import os'
first python checks for
'os.pyc' in the current working directory.
if it doesn't find this, it looks if 'os.py' is there.
If not, then it checks the PYTHONPATH (I believe)
for 'os.pyc' and 'os.py' files.
When the user says 'import x' the name of the
actual filename will be x.pyc or x.py
#---- config.py in C:/exprog
a = 'hi'
b = 'hello'
#---- main.py in C:/exprog
when I run main.py for the first time, it looks for
'config.pyc' because of the 'import config' line.
It doesn't find it, so it compiles 'config.py' into 'config.pyc'
and then imports it. Note that it's not in the global namespace
unless I say 'from config import *'
instead, you have to reference values stored in the 'config' module
using the 'config. ' syntax.
if I were to delete config.py and config.pyc, it would look in
C:/python24/Lib/site-packages/ for a 'config.py' and 'config.pyc'
because that's where my python is installed.
At least that's how I think import works :)
> I'm just guessing, of course. Can anyone explain
> what is really going on under the hood? I'll be
> grateful for a description of the behavior.
> Tutor maillist - Tutor at python.org
More information about the Tutor