How to organize Python files in a (relatively) big project

The Eternal Squire eternalsquire at
Wed Oct 19 21:05:58 CEST 2005

I, too have often come up against the inconvenience of creating
libraries that I want to reuse but that do not want to incorporate into
the Python library.   I came up with this Python library addition to
automagically add the directory of where a module resides that I want
to import to the system path, so that I can simply add the module by
name without needing to worry about anything else.

The large advantage of this is that I can now import from adjacent
directories rather than subordinate ones.    For best results in large
projects with deep tree structure, the paths of the importing script
and the imported module should have at least 3 levels in common.  I do
not consider typing 3 levels of pathing as a hint to be a great

It ain't perfect, it ain't Zen, but for me this has worked from Python
2.2 and up with very few problems for projects up to 1000 files.
Improvements, anyone?

The Eternal Squire
# Place in Python##\Lib
import sys
from   inspect import getfile
from   os.path import abspath

backslash = '\\'

def caller ():

    'name of the calling script'

    frame     = sys._getframe(1)
    if not frame:  return ''
    frame = frame.f_back
    if not frame:  return ''
    result = getfile (frame)
    if result[-4:].lower () in ['.pyc', '.pyo']: result = filename[:-4]
+ '.py'
    return abspath (result)

def append (path):

    'append relative path to system module search path'

    if not path:     return

        calling_script = caller ()

        top_path       = path.split          (backslash)[0]
        where          = calling_script.find (top_path + backslash)

        if where < 0:  return
        result         = calling_script [:where] + path

        if result not in sys.path:  sys.path.append (result)
        return result

        return ''
#---------------------end of

#---------------------"A\B\C\more levels\"-----------------#
#prototypical code, do not try to execute

import relative
relative.append ("\A\B\C\subpath")  # no file extension!
from module import whatsit               # module resides under subpath
whatsit ()

More information about the Python-list mailing list