How to import a Python class that is in a directory above?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Book End
--
Chapters
00:00 How To Import A Python Class That Is In A Directory Above?
00:18 Accepted Answer Score 249
01:27 Answer 2 Score 105
02:17 Answer 3 Score 199
02:24 Answer 4 Score 31
02:33 Thank you
--
Full question
https://stackoverflow.com/questions/1054...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #module #directory #pythonimport
#avk47
ACCEPTED ANSWER
Score 249
from ..subpkg2 import mod
Per the Python docs: When inside a package hierarchy, use two dots, as the import statement doc says:
When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after
fromyou can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you executefrom . import modfrom a module in thepkgpackage then you will end up importingpkg.mod. If you executefrom ..subpkg2 import modfrom withinpkg.subpkg1you will importpkg.subpkg2.mod. The specification for relative imports is contained within PEP 328.
PEP 328 deals with absolute/relative imports.
ANSWER 2
Score 199
import sys
sys.path.append("..") # Adds higher directory to python modules path.
ANSWER 3
Score 105
@gimel's answer is correct if you can guarantee the package hierarchy he mentions. If you can't -- if your real need is as you expressed it, exclusively tied to directories and without any necessary relationship to packaging -- then you need to work on __file__ to find out the parent directory (a couple of os.path.dirname calls will do;-), then (if that directory is not already on sys.path) prepend temporarily insert said dir at the very start of sys.path, __import__, remove said dir again -- messy work indeed, but, "when you must, you must" (and Pyhon strives to never stop the programmer from doing what must be done -- just like the ISO C standard says in the "Spirit of C" section in its preface!-).
Here is an example that may work for you:
import sys
import os.path
sys.path.append(
    os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import module_in_parent_dir
ANSWER 4
Score 31
Import module from a directory which is exactly one level above the current directory:
from .. import module