Mastering Importing Modules in Python

posted 8 min read

Table of Contents

1. Introduction

Modules are one of the key features of Python. Modules are used for code reusability, flexibility, and scalability of Python projects. In this article, we will dive deeper into modules discussing various techniques by which you can use modules effectively.

2. What are modules?

Modules are Python files e.g. module.py that contain Python code. Modules are the basic building blocks of Python projects. Modules can be imported into other Python files. Modules consist of variables, functions, and classes that perform a specific task. Consider the following module math_module.py that we will use in a different Python file.

Create a file named math_module.py and add the following code.

# function that adds two numbers
def add(num1, num2):
    return num1 + num2

# function that subtracts two numbers
def subtract(num1, num2):
    return num1 - num2

# function that multiplies two numbers
def multiply(num1, num2):
    return num1 * num2

Now create another file named main.py in the same directory and add the following code.

# importing the 'math_module' module that we created
import math_module as mth

# calling the functions defined in 'math_module'
result_addition = mth.add(5, 3)
print(f"Result after adding two numbers {result_addition}")
result_subtraction = mth.subtract(10, 4)
print(f"Result after subtracting two numbers {result_addition}")

Now if you run the main.py file you will get the following output.

Great, you have created your module! As you can see, by importing the math_module, we can utilize the functions mth.add() and mth.subtract(), which are defined within a separate file. This importation allows us access to the functionalities encapsulated within the math_module.

3. Types of import statements

There are different ways by which you can import Python modules into your code, you can choose according to your requirements. Following are the different types of import statements that you can use to import modules in your Python code.

Importing modules using import

The import statement followed by the module name is used to import the entire module into your Python code. You have access to all the variables, methods, and classes provided by the module.

Consider the following code.

# importing the entire math module
import math

# using sqrt() function from the math module
print(math.sqrt(16)) 

Following is the output of the above code.

Importing modules using from import

The from import statement allows you to import only the targeted variable, method, or class from the specified module.

Consider the following example.

# importing a single method from the math module
from math import sqrt

print(sqrt(16))

Following is the output of the above code.

Importing modules using import as

The import as statement allows you to assign a new name to the module for your current file, also referred to as alias. Programmers usually use aliases to shorten the module name for ease of usability.

Consider the following code block.

# importing math module with an alias 'm'
import math as m

# using 'm' to call math method 
print(m.sqrt(16))

Following is the output of the above code.

Importing modules using importlib

The importlib module helps programmers to import modules dynamically. Consider the following code block where we are importing the module at runtime.

import importlib

module = "math"
math = importlib.import_module(module) # importing the 'math' module using importlib
print(math.sqrt(16)) 

Following is the output of the above code.

When to use each type of import statement?

You can choose the import statement according to your requirements.

  • The import statement is preferred when you want to access all the variables, methods, and classes of a module.
  • The from import statement is preferred when you want to access a specific functionality.
  • The import as statement is preferred when you want to give a different name to the imported module.
  • The importlib module is used when you want to import the modules dynamically.

4. Importing standard library modules

The Python standard library contains built-in modules that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming. Some of these modules are explicitly designed to encourage and enhance the portability of Python programs by abstracting away platform-specifics into platform-neutral APIs.

Importing the math module

The math module provides access to the mathematical functions. Consider the following code block where we are importing a math module and using its sqrt() and sin() functions.

import math

print(math.sqrt(25)) 
print(math.sin(math.pi / 2)) 

Output of above code block.

Importing the random module

The random module is used for generating random numbers and making random selections. Consider the following code block where we are importing a random module and using its randint() and random() functions.

import random

# generating a random integer between 1 and 10
random_number = random.randint(1, 10)
print(f"Random number between 1 and 10: {random_number}")

# generating a random float number between 0 and 1
random_float = random.random()
print(f"Random number between 0 and 1: {random_float}")

Output of above code block.

5. Importing third-party modules

Third-party libraries are external packages developed by the Python community to address specific programming needs.

Installing third-party modules

You can install any third-party module using a package manager like pip. You can install a package by running pip install <package_name> in your command-line interface.

Let's install pandas a third party module using pip

Importing and using third-party modules

Once pandas is successfully installed we can use it, But first we have to import pandas as import pandas as pd. Consider the below code block.

import pandas as pd

# creating a dataframe
data = {'Name': ['Uzair', 'Ali', 'Hamza'],
'Age': [30, 19, 35]}
df = pd.DataFrame(data)
print(df)

Below is the output of the above code block.

6. Handling module errors and exceptions

You might be facing some issues while importing modules in Python, so let's discuss the common issues that can occur.

Common errors and exceptions

Following are some errors that you might face while working with the modules.

Module not found error

This error occurs when you are trying to import a module that does not exist. Consider the following code block where we are trying to import a module that does not exist.

import mathematics as mth

print(mth.sqrt(25))

If you run the above code you will get the error ModuleNotFoundError: No module named 'mathematics', Because we are trying to import a module name mathematics that is not defined in the Python standard library.

Warning: Check the spelling of the module you want to import.

Attribute error

The attribute error occurs when Python cannot locate the specified attribute or function. Consider the following code block where we are trying to use a function that is not defined in math module.

import math

print(math.sqroot(25))

If you run the above code you will get the error AttributeError: module 'math' has no attribute 'sqroot'. Did you mean: 'sqrt'?. The error is because we are trying to access a method name sqroot() which is not defined in the math module.

Import error

The import error usually occurs due to circular imports. Consider the following code blocks.

Consider we have a file name module1.py where we are importing a module module2.

import module2
...

Consider another file named module2.py in which we are importing a module module1

import module1
...

Now, when we try to run module1.py using the command python module1.py, python attempts to import module2.py. However, while importing module2.py, it encounters an import statement for module1.py, which is not fully initialized yet due to the circular dependency. In this case you will get the import error as ImportError: cannot import name 'module1' from partially initialized module 'module2'

7. Best practices for importing modules

You can follow the following best practices while importing the modules to ensure code readability, maintainability, and compatibility across your Python projects.

Best practices and optimization

  • Don't populate the code with import statements, only import those modules that are required.
  • Use aliases to give short and meaningful names to the imported modules.
  • Avoid circular imports by carefully organizing your code and dependencies.
  • Use virtual environments to isolate the project dependencies.
FAQ Q. What is a module? A. Modules are Python files e.g. `module.py` that contain Python code.
Q. How do you import modules in Python? A. You can import modules using statements like 'import', 'from import', and 'import as' depending on your requirement.
Q. How can I install and use third-party modules in Python? A. You can install a third-party module by using a package manager like 'pip' and then import it like other modules.
Q. When should I use dynamic imports with importlib in Python? A. You should use importlib when you want to import modules dynamically at runtime or under some conditions.

8. Conclusion

Modules are the basic building blocks of any programming language; they allow you to access various built-in functionalities that you can easily use in your project. In this article, we have seen various import statements like import, import as, and from import which allow you to import the modules in a specific way. You can dynamically import modules using importlib. You can import third-party modules using package managers like pip. We talked about the common errors that can occur while importing modules like ModuleNotFound, AttributeError, and circular imports. Finally, we discussed best practices you can follow while importing the modules.

9. References

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Modules and Packages: Using Standard Library Modules

muhammaduzairrazaq - Jul 12, 2024

Mastering Lambda Functions in Python: A comprehensive Guide

Abdul Daim - May 6, 2024

Mastering Data Visualization with Matplotlib in Python

Muzzamil Abbas - Apr 18, 2024

Mastering Reading and Writing CSV Files in Python

Abdul Daim - Mar 27, 2024

Python Installing External Packages Sources

muhammaduzairrazaq - Mar 25, 2024
chevron_left