Python Imports From The Directory Above

17,195

Solution 1

import sys
sys.path.append('/your/dir/goes/here')
from base import foo

Something like that should permit you to import stuff from any directory of your choosing.

Solution 2

To enable relative import, add main/__init__.py to make main directory into a Python package. The main's parent directory should be in sys.path.

Share:
17,195
bobthemac
Author by

bobthemac

Updated on June 05, 2022

Comments

  • bobthemac
    bobthemac about 2 years

    I have a directory structure for my python application where in the main folder I have a folder called handlers and in that file I have a base.py that all handlers should inherit from . I also have a folder called users that contains all the handlers relating to users.

    \main
          \handlers
          base.py
          __init__.py
          \users
                    __init__.py
                    authenticated.py
                    logout.py   
    

    My issue is I can't import the base in any file in the users folder but can import from the users folder. I know that I have to do something like bellow

    from ..handlers import *    
    

    But that does not work for some reason all I am trying to do is import base.py into files in the users directory and other directorys I add at a later date.

  • Joran Beasley
    Joran Beasley over 10 years
    may want to insert it at the beginning of path rather than the end, but yeah +1
  • bobthemac
    bobthemac over 10 years
    This didn't work still getting a no module named error. I shouldn't really be doing this either as I am unsure if it is compatible with google app engine that it is running on.
  • Zoey Hewll
    Zoey Hewll over 6 years
    Note, you can use relative paths (eg './' and '../') with this method, in addition to absolute paths (eg '/home/username/code')