Import from sibling directory

Question:

I have a Python class called “ClassA” and another Python class which is supposed to import ClassA which is “ClassB”. The directory structure is as follows:

MainDir
../Dir
..../DirA/ClassA
..../DirB/ClassB

How would I use sys.path so that ClassB can use ClassA?

Asked By: skylerl

||

Answers:

You can use relative import (example from link, current module – A.B.C):

from . import D                 # Imports A.B.D
from .. import E                # Imports A.E
from ..F import G               # Imports A.F.G
Answered By: crazylammer

You really should be using packages. Then MainDir is placed at a point in the file system on sys.path (e.g. …/site-packages), then you can say in ClassB:

from MainDir.Dir.DirA import ClassA # which is actually a module

You just have to place files named __init__.py in each directory to make it a package hierarchy.

Answered By: Keith

as a literal answer to the question ‘Python Import from parent directory‘:

to import ‘mymodule’ that is in the parent directory of your current module:

import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0,parentdir) 
import mymodule

edit
Unfortunately, the __file__ attribute is not always set.
A more secure way to get the parentdir is through the inspect module:

import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
Answered By: Remi
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.