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

Показать описание
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:
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:
Комментарии