Import from sibling directory
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 osparentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))os.sys.path.insert(0,parentdir) import mymodule
editUnfortunately, the __file__
attribute is not always set.A more secure way to get the parentdir is through the inspect module:
import inspectcurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))parentdir = os.path.dirname(currentdir)
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.