HOW TO: Do Relative & Absolute Imports (Python Error Explained)

preview_player
Показать описание
To display structure of directory using tree, put

inside ~/.bash_profile

Then run:

source ~/.bash_profile

Let’s start with this toy project structure:
The root directory contains ‘package’ which is a package because it has __init__.py

Inside package you have moduleA.py module

You also have a subpackage called ‘subpackage1’ which also has __init__.py to tell python it is part of a package.

Inside subpackage1 we have submoduleA.

Let’s look at relative imports first: let’s say in submoduleA we want to use the functions from moduleA.

We use .. to go back to a previous folder. Then import the module we want.

To run this script directly from the terminal, make sure you are running from the folder where the package is located; NOT INSIDE THE PACKAGE.

We can also do absolute imports. Let’s say in moduleA we want to use the functions from submoduleA.

Again, to run this module directly from the terminal, make sure you are running from the folder where the package is located; NOT INSIDE THE PACKAGE.

If you want to run it interactively e.g. in Spyder. You should pip install your package in an editable state and then use absolute imports.

Source:
Рекомендации по теме
Комментарии
Автор

Thank you so much, that saved my working day!

sonpham
Автор

import sys
sys.path.append("..")
try: from ..user.apps.Calculator import *
except: from ..user.apps.Calculator import *
calc.main()

Doesn't work. Why?

Blxxy
Автор

Thanks so much. This is very helpful! But what if we r still developing the codes? I mean the package is not complete, and thus we don't want to install it into the library. What should we do in such a case if we are using the Spider or VSCode? I know PyCharm has the functionality to define where is the root of project file.

jimmy_bytheway_
Автор

try except thing is unique, I have never seen anybody else using this

ayushman_sr
Автор

Typically you don't run your script from root... but from somewhere you might have your data to work on so that doesn't work.
The other method of python -m .... is also a headache to write.
Installing package... just doing the monkey-work over and over.
I'm really disappointed with python. This is just terrible.

rvoros