From knowledge import improvement

2014-04-02 UPDATE: The only reason ‘from tools.DbSession..’ (see below) worked was because ‘tools’ was a subdirectory of the directory I was in (‘projects’). Had NOTHING do to with the PATH variable. I FINALLY found the solution!

In my post about importing Python modules, I wrote that I preferred setting the PATH variable in my code instead of changing my computer’s PATH variable. With so much of my code being new, that did not seem like much of a burden. It was, however, pointed out to me that it could become a major hassle down the road, if I have tons of scripts set to a certain path using sys.path.append(). They would all need to be updated if used on a computer with a different directory structure, or even if I just moved my code around on my current computer. I had previously tried working with the PATH setting without success, so for the time being it was easier to specify it in code.

Now, I am happy to report, I have discovered the better way.

I have a class called ‘DbSession’ in the module ‘DbSession.py.’ I keep it, and other modules that I want to share among all my projects, in a directory called ‘tools.’ Project-specific code is kept in project folders which reside in the same parent directory as does ‘tools.’

Here’s how I figured it out how to make ‘DbSession’ available to all:

First,  I added the ‘tools’ directory to my system PATH variable and confirmed it was correct. Here is is displayed in a command prompt window, including my ‘tools’ directory:

echo %PATH%
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;
C:\Python33;C:\Python33\Lib\site-packages;
C:\Documents and Settings\Rob\My Documents\Dropbox\projects\tools;

I run Python from the ‘tools’ directory and confirm the import works, without errors (that is, it does nothing but put me back to the Python prompt), from there:

>>>from DbSession import DbSession
>>>

I run Python from a different directory (‘projects’) and retry the import. It chokes:

>>>from DbSession import DbSession
Traceback (most recent call last):
File “”, line 1, in
ImportError: No module named ‘DbSession’

Huh? I thought I had the ‘tools’ directory in my PATH variable, so shouldn’t Python be able to see what’s in it?

Behold, the kicker:

>>>from tools.DbSession import DbSession
>>>

And there we have it! Apparently, when a directory for modules is specified in PATH, the name of that directory must also be specified in the import statement when attempting to access those modules.

Now, at last, I’ve found the right path to the right use of PATH.