Change language

Absolute and relative imports in Python

|

Importing in Python is similar to #include header_file in C / C++. Python modules can access code from another module by importing a file / function using import. The import statement is the most common way to call importing equipment, but it is not the only way. The import statement consists of the keyword import and the name of the module.

The import statement includes two operations, it searches for a module and associates the search result with the name in the local scope. When a module is imported, Python runs all the code in the module file and makes it available to the importer file.

When a module is imported, the interpreter first looks for it in sys.modules , which is the cache of all modules that were previously imported. If not found, it searches all builtins with that name, if found, the interpreter executes all the code and makes it available to the file. If the module is not found, it looks for a file with the same name in the directory listing specified by the sys.path variable. 
sys.path — it is a variable containing a list of paths that contains libraries, packages, and a directory containing the entry script. For example, a module named math is imported and the interpreter looks for it in built-in modules, if not found, it looks for a file named math.py in the directory list given by sys.path .

# Import Python program
# math module

 

import math

print (math.pi)

Exit:

 3.141592653589793 

Syntax of import statements:
The user can import both packages and modules. (Note that importing a package essentially imports the __init__.py package file as a module.) The user can also import specific objects from a package or module. 
There are usually two types of import syntax. When you use the former, you import the resource directly.

 import gfg 

gfg can be a package or a module.

When the user uses second syntax, the user is importing a resource from another package or module.

 from gfg import geek 

geek can be a module, subpackage, or object such as a class or function.

Styling import statements:
PEP8 , the official style guide for python, contains a set of rules on how to formulate python code to maximize its readability. There are a few things to consider when writing imports:

  1. Imports should always be written at the top of the file, right after any module comments and docstrings.
  2. Imports should usually be separated by a space .
  3. Imports must be grouped in the following order.
  • Standard library imports (Python built-in modules)
  • Related third party imports.
  • Importing Applications / Libraries Locally

It is also good to arrange the imports alphabetically in each import group.

# Display Python program
# how to style import statements

 

import math

import os  

 
# Third-party import

from flask import Flask

from flask_restful import Api

from flask_sqlalchemy import SQLAlchemy

 
# Import local applications

from local_module import local_class

from local_package import local_function

Absolute imports:

Absolute imports include the full path, that is, from the project root to the desired module. Absolute import state that the resource should be imported using the full path from the project root.

Syntax and practical examples:
Let’s see, we have the following directory structure :

Here is the directory with named project, in which pkg1 has two subdirectories, namely pkg1 , pkg2 pkg1 has two modules, module1 and module2. 
pkg2 contains three modules, module3, module4, __init__.py and one subpackage name subpkg1 which contains module5.py. Let’s assume the following:

  • pkg1 / module1.py contains the function fun1
  • pkg2 / module3. py contains fun2
  • pkg2 / subpkg1 / module5.py contains fun3

# Show Python program
# practical example
# absolute imports

 
# import fun1 from pkg1 / module1

from pkg1. import module1 import fun1

 

from pkg1 import module2

 
# import fun2 from pkg2 / module3

from pkg2 import module3 import fun2

 
# import fun3 from pkg2 / subpkg1 / module5

from pkg2.subpkg1.module5 import fun3

In this example, we will import modules by writing the full path from its root folder.

Pros and cons of absolute import:
Pros :

  • Absolute import is very useful because it understandable and understandable.
  • Absolute imports are easy to define exactly where and the resource is imported just by looking at the statement.
  • The absolute import remains valid even if the current location of the import statement is changed.

Cons:
If the directory structure is very large, it makes no sense to use an absolute import. In this case, using relative imports works well.

 from pkg1.subpkg2.subpkg3.subpkg4.module5 import fun6 

Relative imports:

Relative imports specifies an object or a module imported from its current location, that is, the location where the import statement is located. There are two types of relative imports:

  • Implicit relative imports:
  • Implicit relative imports were rejected in Python (3.x).

  • Explicit relative imports :
  • Explicit relative imports have been approved in Python (3.x).

Syntax and case studies:
Relative syntax import depends on the current location as well as the location of the imported module or object. Relative imports use a period (.) To indicate a location. One dot indicates that the module is in the current directory, two dots indicate that the module is in its parent directory at its current location, and three dots indicate that it is in the parent directory, and so on. 
Let’s see, we have the following directory structure:

Let’s assume the following:

  • pkg1 / module1.py contains the function fun1
  • pkg2 / module3.py contains fun2
  • pkg2 / subpkg1 / module5.py contains fun3

# Show Python program
# practical example
# relative imports

 
# import fun1 into pkg1 / module1.py

from . module1 import fun1

 
# import fun2 and fun3 into pkg2 / module3.py

from . module3 import fun2

from . subpackage1.module5 import fun3

Pros and cons of relative imports:
Pros :

  • Working with relative imports is short and straightforward.
  • Based on current location, this reduces the complexity of the import statement.
    • Cons :

      • Relative imports are not as readable as absolute imports
      • Using relative imports is not easy because it is very difficult to locate the module.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically