Wednesday, July 23, 2014

Some notes on Python imports and project organization

One majorly annoying thing for Pythonistas is the search path that the import command uses. When I was a beginner and wanted to get cracking I'd simply add whatever I was working on to PYTHONPATH, not wanting to get bogged down in silly details (that's what we were using Python for, right?).

I learned my lesson when I "forked" one of my projects (by duplicating the directory - give me a break, I wasn't born learning version control systems) and spent several hours trying to figure out why changes to a file I was making did not show up when I ran the code - Python, of course, was picking up the old version of the module in the original directory.

My current strategies, in somewhat random order, for project organization and testing are:

Project organization

   |             |------->  (empty)
   |             |-------> root level modules 
   |             |-------> submodule1
   |             |    |---------------> (empty)
   |             |    |----> sub modules
   |             |-------> submodule2
   |                  |---------------> (empty)
   |                  |----> sub modules
                 |------->  import sys; sys.path.append('../mainmodule')
                 |-------> root level module tests 
                 |-------> submodule1
                 |    |---------------> (empty)
                 |    |----> sub module tests
                 |-------> submodule2
                      |---------------> (empty)
                      |----> sub module tests

An important lesson is a) not to forget the files and b) to add relevant paths to sys.path in when needed.

Using this directory structure allows me to use sphinx for the documentation (the source root goes in in docs) and allows me to invoke nosetests by doing

nosetests tests

and the path appending going on in tests/ allows me to import any part of the module in any test script just as I would from a different application after the application has been installed using

No comments:

Post a Comment