The Python Oracle

Importing modules from parent folder

--------------------------------------------------
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: Luau

--

Chapters
00:00 Importing Modules From Parent Folder
00:32 Accepted Answer Score 155
00:52 Answer 2 Score 754
01:09 Answer 3 Score 493
01:42 Answer 4 Score 147
02:04 Thank you

--

Full question
https://stackoverflow.com/questions/7140...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #module #path #directory #pythonimport

#avk47



ANSWER 1

Score 754


You could use relative imports (Python >= 2.5):

from ... import nib

(What’s New in Python 2.5) PEP 328: Absolute and Relative Imports




ANSWER 2

Score 493


Relative imports (as in from .. import mymodule) only work in a package. To import 'mymodule' that is in the parent directory of your current module:

import os
import sys
import inspect

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir) 

import mymodule

Note: The __file__ attribute is not always given. Instead of using os.path.abspath(__file__) I suggest using the inspect module to retrieve the filename (and path) of the current file.




ACCEPTED ANSWER

Score 155


It seems that the problem is not related to the module being in a parent directory or anything like that.

You need to add the directory that contains ptdraft to PYTHONPATH

You said that import nib worked with you, that probably means that you added ptdraft itself (not its parent) to PYTHONPATH.




ANSWER 4

Score 147


You can use an OS-dependent path in "module search path" which is listed in sys.path.

So you can easily add the parent directory like the following:

import sys
sys.path.insert(0, '..')

If you want to add the parent-parent directory,

sys.path.insert(0, '../..')

This works both in Python 2 and Python 3.