Absolute vs Relative Importing In Python

Absolute Vs Relative Importing

Hello fellow learner! Today we are going to learn about the differences between Absolute vs Relative Importing in Python.

Every time you need a direct function to implement anything in our program we can directly import it from the right library! Now let’s learn about Absolute and Relative Importing in Python programming.

What is Absolute Importing?

When we import modules through absolute importing, we need to include the full path of the module after the import keyword.

The complete path includes the main module/library along with the submodules or functions to be used in the program.

Advantages of Absolute Importing

  1. This approach is clear, straightforward and easy to understand
  2. The absolute import commands remain valid even if the current location of the import statement is changed later.

Disadvantages of Absolute Importing

Let us suppose, we have to import a function that is present at a deeper layer in the root module. The absolute import command for such module will look something like this:

from package_1.sub_package_1.sub_package2.sub_package3.module1 import req_function

If the required function is present even deeper in the layers then it’s gonna get really messy and complicated. That’s when the Relative Importing comes to the rescue!

What is Relative Importing?

In relative approach, we can import a function relative to a certain package or sub package’s location which makes it a better way of importing modules and functions.

We have two types of relative importing approaches namely implicit and explicit approach but the implicit approach doesn’t support with Python3.x versions anymore.

The relative importing approach is illustrated below:

from .sub_package_x.module_5 import req_function

The initial . takes into consideration all the previous host modules/libraries and we don’t need to write the whole thing like absolute importing.

Advantages of Relative Importing

  1. The import statements are short and crisp.
  2. Reduces the complexity of the import statement

Disadvantages of Relative Importing

  1. This approach is not very readable and the programmer is unaware of many root modules.
  2. The programmer is unaware of the origin of the function we are importing

Conclusion – Absolute vs Relative Importing

Now you know the basic differences between absolute vs relative importing approaches.

I would recommend you to go for absolute approach as a beginner and as you advance your coding experience you can start using relative approach.