Appending paths relative to the current file to sys.path

Greg McIntyre greg at notmyrealaddress.com
Mon Sep 12 02:21:50 EDT 2005


Out of interest, are there any standard Python modules that do this:

def appendRelativeIncludePath(*relpath):
   dir = os.path.abspath(os.path.join(os.path.dirname(__file__), *relpath))
   if not dir in sys.path:
     sys.path.append(dir)

I ask because I often find myself doing this:

----
# myproject/lib/mymodule/test/test.py

if __name__ == '__main__':
   import os.path
   import sys

   dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',  
'..'))
   if not dir in sys.path:
       sys.path.append(dir)

   import mymodule  # it's always 2 directories up from here

----

And it seems like a lot to type so often. I can't factor out this  
functionality unless I create a little module for doing this and install  
it in a standard include path. You see I dream of doing this:

----
# myproject/lib/mymodule/test/test.py

if __name__ == '__main__':
   import astandardmodule
   astandardmodule.appendRelativeIncludePath('..', '..')
   import mymodule

----

Which, as you can see, is much shorter. ;)

-- 
Greg McIntyre



More information about the Python-list mailing list