Absolute vs Relative Imports in Python

Posted in /   /  

Absolute vs Relative Imports in Python
vinaykhatri

Vinay Khatri
Last updated on December 10, 2024

    When you work on a big Python project, you will be dividing the Python code into multiple Python files. This splitting of code into multiple files gives a modular look to the project, and it is one of the best ways to write clean code.

    Mostly, all the top Python libraries are written using multiple Python files known as Python modules and reside in multiple directories or folders known as Python packages . The Python import statement makes it easy for Pythonistas to use the code of one Python file in another.

    However, still many Python beginner and intermediate learners find the import statement confusing and do not know the difference between relative and absolute imports in Python (absolute vs relative imports).

    Here in this Python tutorial, we will walk you through the Python import statement and discuss the difference between relative and absolute imports.

    What is Import in Python?

    import is a Python keyword that is used for importing code in the current Python script. The Python import statement is generally used when we want to access another Python file, Python module, or Python package in the current script.

    For instance, suppose you want to use the Python math module to round off a floating-point number to a whole number . First, you need to import the math module in your current script before using the floor() and ceil() methods.

    Example #error

    >>> num = 39.7
    >>> math.floor(num)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'math' is not defined

    If you do not import the module you wish to use in your Python script, then Python will throw a NameError . Example

    >>> import math
    >>> num = 39.7
    >>> math.floor(num)
    39

    The import statement will add the module object to the current scope of your program. So if you want to use the imported module throughout any section of the program, you need to mention the import statement at the top of your Python program or script.

    How Does The Import Statement Work?

    The import statement goes through a lot behind the scenes. First, the import statement looks for the module or package in the sys.modules . The sys.module section stores all the previous imported code, and it is like cached storage for already imported modules.

    If the import does not find the module or package in the sys.module section, it starts searching through the Python Standard Libraries. Still, if the import does not find the module in the Python Standard Libraries , it starts searching the same in the installed libraries section or system.path .

    Even if the import statement is not able to find the module or package, it throws a ModuleNotFoundError. The search for import search starts from your current directory, and then it goes to the Python built-in Standard Libraries, and at last look for the same in the installed libraries.

    Import Statement Syntax

    Generally, we mention the import statement at the top of our Python program or script, so we can access the module from any section of the program. Names of modules and packages are case-sensitive, and thus, make sure you are writing the correct name.

    import module_name

    or

    import package_name

    The import statement imports the complete module or packages to your current Python program or script. However, Python also provides the from statement that works along with import . This makes the import statement sophisticated.

    from package_name import module
    or
    
    from module_name import module_function

    Example

    #import module
    >>> import math
    >>> num = 34.88
    >>> math.floor(num)
    34
    
    #from module import module function
    >>> from math import floor
    >>> num =35.9
    >>> floor(num)
    35
    
    #from module import all functions or submodule
    >>> from math import *
    >>> num =48.37
    >>> ceil(num)
    49

    Types of Python Imports

    You can use two different types of import statements to import a module or package to your current Python program. These are:

    1. Absolute Imports
    2. Relative Imports

    1. Python Absolute Imports

    In the Python absolute import, we include the absolute path of the module from its root directory or folder. To separate every subdirectory or module, we use the period symbol (.). Absolute imports are generally used when we only want to import specific functions or sub-modules from modules or packages.

    Syntax

    ??? project
    |   ??? package_A
    |   ?   ??? __init__.py 
    |   ?   ??? module_A.py
    |   ?   ??? module_B.py
    |   ??? package_B
    |      ??? __init__.py
    |      ??? module_C.py
    |      ??? module_D.py
    |      ??? subpackage_A
    |          ??? module_E.py

    For instance, if you want to access a method function_E that is written inside the module_E, you need to specify the absolute path to module_E.py and grab the function_E method. For example:

    from project.pakage_B.subpackage_A.module_E import function_E.

    Using the same syntax, you can access any module and package of the project.

    Pros of Absolute Import

    • Absolute imports are clean and give a brief idea about the method or module you want to use.
    • It also becomes easy for the interpreter to directly look for the specified module.

    Cons of Absolute Import

    • In some cases, the absolute import becomes quite long because of subfolders or modules. And this could expand the import statement into two lines.
    • In absolute importing, you have to be careful while mentioning the root folder. If you are in the subfolder, then the above folder will be your root folder.

    2. Python Relative Imports

    In relative imports, we mention the import statement relative to the location of the current Python program or where we are using the import statement.

    Syntax

    ??? project1
    |   ??? package_A
    |   ?   ??? __init__.py 
    |   ?   ??? module_A.py
    |   ?   ??? module_B.py
    |   ?   ??? CurrentProgram.py
    |   ??? package_B
    |      ??? __init__.py
    |      ??? module_C.py
    |      ??? module_D.py
    |      ??? subpackage_B
    |          ??? module_E.py
    |------project2

    Suppose you are at CurrentProgram.py , and you want to access the function_B method from module_B.py . So, instead of using the absolute import, it would be a great practice to use the relative import because CurrentProgram.py and module_B.py are in the same location. In relative import, we use the (.) dot notation to represent the current directory. #CurrentProgram.py

    from .module_B import function_B

    Access the module_E method function_E from module_C . #package_B/module_C

    .subpackage_B.module_E import function_E

    Pros of Relative Import

    • For small projects where you are not using many sub-folders, relative import provides a cleaner way to import Python modules .
    • The relative import rarely gets too long.

    Cons of Relative Import

    • If you are working on a project with multiple subfolders, their relative import could get messy.
    • For shared projects, relative imports are hard to read.

    Absolute vs Relative Imports in Python: A Head-to-Head Comparison

    Python Absolute Python Relative
    In absolute import, we specify the complete path of the module location from its root directory or package. In relative impart, we specify the path of the module location from the current or working Python program or script.
    Absolute imports are generally long. Relative imports are generally short.
    Absolute imports are more readable and clearer. Relative imports are less clear.

    Conclusion

    That was all about absolute vs relative imports in Python. Generally, Python developers prefer absolute import when they are working on shared or big projects. Because there, they want to make sure that other developers could also get the full path of the import module.

    Relative imports are helpful when you are working alone on a Python project, or the module is in the same directory where you are importing the module.

    While importing the module, be careful with the (.) dot notation. In absolute imports, it is used to separate the modules and sub-packages, and in relative imports, it is used to represent the current directory and separate modules and sub-packages.

    People are also reading:

    FAQs


    While absolute import entails the path from a project's root folder to the desired module, relative import entails the path starting from the path of the current module to the desired module.

    The two types of relative imports are implicit relative imports and explicit relative imports.

    Python 3.x supports explicit relative imports.

    Built-in and user-defined modules are the two types of modules in Python.

    You should use relative import when you are alone working on a Python project or when the module is in the same directory where you are importing the module.

    Leave a Comment on this Post

    0 Comments