Jeremy Minton About
Python importing from parent folder
Posted by Jeremy Minton, ,

Apparently there is some discussion somewhere about being able to import from parent directories. Long story short, I think, is that it was deemed that this is a poor way to structure modules, however, for work which contains run scripts in folder within the working directory this would be a useful functionality.

There are two ways to approach this which I have found.

If in a module, then relative paths can be used (python >= 2.5):

from .. import my_module

This won’t work from a script and so modification to the sys path is a reasonable approach:

import os,sys,inspect
current_direcotry = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_directory = os.path.dirname(current_directory)
sys.path.insert(0,parent_directory)