In this post, we will learn How to do relative imports in Python where the relative import is the importing of the packages which are located in some other locations than the current file and we use the dot(.) notations for specifying the location of the package.
As we know relative import is the import of the package from the same package or module and we use dot (.) notation to specify the location of the module which we are importing. And there we need to keep a thing in mind which is the number of dots that could be used for making clear the level up the package hierarchy which we have to cover before reaching the specified package.
Here we have given an example to understand it better where we explained the directory of the package we are going to use first here
my_package/ ├── __init__.py ├── module1.py └── module2.py
Here it is the directory we want to access and the code for importing this directory package is given below where we can get to know how we can use in our code.
from . import module2
Here we used the dot (.) to show that the package we want to import is located at the same location where we are using so there is no need to specify the whole path of the location.
Here we can also use multiple dots(.) that simply refer to the levels of the package and double dots mean a higher level package for example, follow the example given below to understand it better.
from .. import parent_module
One thing we need to keep in mind here is if we want to access the module outside the package we need to use the top level modules.
In addition to that we need to keep in mind that relative import can sometimes be tricky to get right, and may not always work as expected. In general, it’s best to use absolute import (e.g import any package .any module) when importing modules from other packages, and only use relative import when importing modules within the same package it all depend upon the requirements what the project is demanding for the timing.
To learn more about How to do relative import in Python visit: by stack overflow.
To learn more about solutions to different problems and tutorials for the concepts we need to know to work on programming along with different ways to solve any generally asked problems: How To Pass-Variables From A Java & all Client To A Linux/Ubuntu Server Which Is Running C?.