Skip to content Skip to sidebar Skip to footer

Python Relative Import

I'm trying to make a relative import in python. but I can't understand the syntax and everytime I search for it here in SO, I can't get an answer: Here is my folder structure: Root

Solution 1:

You have to add the directory to your python path.

import sys
sys.path.append("/libraries") 

But I think it might be better to either put the libraries in the folders of the projects that need it or just install them to one of the standard places already in sys.path.

Solution 2:

I don't think it can be done with a simple import statement. What I would do is to append the relative path to your library folder to sys.path like this:

import sys
sys.path.append('../../')
from libraries import mylibrary

Note that this works only if you start the python interpreter from the projects/project directory.

Solution 3:

There is an unfortunate source of confusion with relative imports. When you first learn about them, you think that they allow you to use generally relative file/directory paths to refer to individual files that will be imported. (Or at least, I thought so.) In fact, they only allow you to use relative paths within a package. This means that certain modules within a package can use relative-import syntax when they need to import other modules from within the same package.

In your example, myproject.py is not in the same package as mylibrary, and in fact is not in any package, so there is no way to use relative imports from inside myproject.py . Relative imports just don't apply in that situation.

There are a couple things you can do to get the effect you want. One is to put your libraries in subdirectories of the system site-packages directory. Another is to put .PTH files in the system site-package directory, with those .PTH files containing the paths to the places where your libraries are stored. Another is to use PYTHONPATH to point to directories where you store your libraries.

Post a Comment for "Python Relative Import"