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

Опубликовано: 28 Сентябрь 2024
на канале: chinamatt
10,253
96

To display structure of directory using tree, put

alias tree='tree.com //f'

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.

We use from package.subpackage1.submoduleA import *, package here represents the top level package.

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:
https://stackoverflow.com/questions/1....
https://stackoverflow.com/questions/7...