Python relative import

I am trying to do relative imports in python. but I can’t understand the syntax and every time I look for it here in SO, I can’t get the answer:

Here is my folder structure:

Root libraries mylibrary __init__ projects project myproject.py 

and I want to import 'mylibrary' using a relative path, what is the syntax for this?

+4
source share
3 answers

You must add the directory to your python path.

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

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

+3
source

I do not think that this can be done with a simple import statement. I would do to add the relative path to the library folder in sys.path as follows:

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

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

+3
source

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

In your example, myproject.py is not in the same package as mylibrary, and in fact it is not in any package, so there is no way to use relative imports from myproject.py. Relative imports simply do not apply in this situation.

There are several things you can do to get the effect you want. One of them is to place your libraries in subdirectories of the system-packages system directory. Another is to place .PTH files in the system package site directory with such .PTH files containing paths to the storage locations of your libraries. Another is to use PYTHONPATH to point to the directories in which you store your libraries.

+3
source

Source: https://habr.com/ru/post/1415733/


All Articles