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


ProjectName
   |--------->Readme
   |--------->setup.py
   |--------->docs
   |--------->mainmodule
   |             |------->__init__.py  (empty)
   |             |-------> root level modules 
   |             |-------> submodule1
   |             |    |---------------> __init__.py (empty)
   |             |    |----> sub modules
   |             |-------> submodule2
   |                  |---------------> __init__.py (empty)
   |                  |----> sub modules
   |
   |--------->tests
                 |------->__init__.py  import sys; sys.path.append('../mainmodule')
                 |-------> root level module tests 
                 |-------> submodule1
                 |    |---------------> __init__.py (empty)
                 |    |----> sub module tests
                 |-------> submodule2
                      |---------------> __init__.py (empty)
                      |----> sub module tests

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

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

nosetests tests

and the path appending going on in tests/__init__.py 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 setup.py

No comments:

Post a Comment