Python 101 (part 7): Dinner With A Hungry Giant - Love Bytes
(Page 4 of 9 )
The "import" statement looks for module files in the directories specified in the $PYTHONPATH environment variable. If the named module isn't found in these directories, it returns an error - as the following example demonstrates:
>>> import SQLfunctions
Traceback (innermost last):
File "", line 1, in ?
ImportError: No module named SQLfunctions
>>>
Once you add the directory containing the module to the $PYTHONPATH variable and restart the interpreter, Python should find and import your module without any errors (you can also modify the search path via the built-in "sys" module - more on this later.)
In case Python finds more than one module with the specified name, the first one is used.
The first time Python imports a module, it automatically compiles the module as saves it as bytecode; this bytecode file has the same name as the module file, but ends in a .pyc extension. These .pyc files are automatically recompiled if the module changes in any way. If you take a look at your working directory after importing and using one or more modules in a Python program, you'll notice a bunch of these .pyc files scattered around - Python stores these to speed up the module the next time it's called.
$ ls -l
-rw-rw-r-- 77 Jul 23 23:04 dewey.py
-rw-rw-r-- 181 Jul 23 23:05 dewey.pyc
-rw-rw-r-- 98 Jul 23 23:04 huey.py
-rw-rw-r-- 202 Jul 23 23:22 huey.pyc
-rw-rw-r-- 244 Jul 23 22:49 temperature.py
-rw-rw-r-- 435 Jul 23 22:50 temperature.pyc
-rwxrwxr-x 222 Jun 8 10:50 module_test.py
If you play with this a little, you'll see that I told a little white lie a few paragraphs back, when I said that Python could only import a module if it was located in a directory named in $PYTHONPATH. In fact, even if the module isn't located in the search path, but its corresponding bytecode is present, Python will still import and use the module.
Consider the following example, where the working directory (which is in the search path) doesn't contain the module source, but *does* contain the compiled bytecode version - Python goes ahead and uses the bytecode version without blinking:
$ ls -l
-rw-rw-r-- 435 Jul 23 22:50 temperature.pyc
-rwxrwxr-x 222 Jun 8 10:50 module_test.py
$ python
>>> import temperature
>>> temperature.tempConv(95, "f")
35.0
>>>
Next: Enter The Hungry Giant >>
More Python Articles
More By Vikram Vaswani, (c) Melonfire