Here's another "blog to self" to archive stuff that I keep forgetting.
The pythonpath variable is a system variable which tells the python interpreter where to look for python modules when an import statement is called. The current shell's pythonpath is a list and can be found by
>>>import sys
>>>sys.path
on my system this returns
[' ','/home/neil/pycode', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', etc....
the first item on this list is ' ', which means that the current shell's directory is checked, and '/usr/lib/python2.5' is no surprise. Also on the path (not shown for brevity) are some 3rd party python modules I've installed such as wxpython, PIL, PyQt4 etc....
but hang on... what is that '/home/neil/pycode'?
That is there (and unlike other methods survives a reboot) thanks to this line in my .profile file
export PYTHONPATH=/home/neil/pycode
pycode is a directory where I put my own python modules.
Any modules in this directory can be imported by others.
However, I need to be careful of contaminating the python namespace.
Example - If I save a module I've named "sys.py" in there this will be found BEFORE the sys module native to python (because the pythonpath is checked in order)
so.. here's one way around that problem, and A neat way of organising your modules to boot.
Python "Packages".
Packages are just folders which contain other modules AND a file named __init__.py (this file can be and usually is empty)
Example I have a package called "norman" which is simply a folder of modules (/home/neil/pycode/norman) and thanks to the __init__.py trick, I can do import statements like...
>>>from norman import mymodule
if I am still stupid enough to want to write a module called sys.py, and put it in the norman folder... it won't get imported by
>>>import sys
but would by
>>>from norman import sys
or
>>>from norman import *
but we don't do that, do we??
No comments:
Post a Comment