Table of Contents
1. Introduction
Modules and packages are one of the key features of Python. They are used for code reusability, flexibility, and scalability of Python projects. In this article, we will dive deeper into modules and packages discussing various techniques by which you can use them 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. What are packages?
Packages are the directories that contains Python modules, it also contains a file __init__.py
that indicate the directory is a package. You can also make your custom packages just like we create a module in above example, but for now lets import a package from Python Standard Library.
Consider the following example where we are importing a module urllib.request
from urllib
package.
import urllib.request
response = urllib.request.urlopen('https://www.example.com')
html = response.read()
print(html[:200]) # print the first 200 characters from the HTML content
Following is the output of the above code.

Before moving forward consider the directory structure of urllib.

If you notice urllib contains various python files i.e., errors.py, request.py also called modules and one more file init.py now if you revisit the definition of package, you will find out that urllib clearly follows it.
4. Importing standard library modules/packages
The Python standard library contains built-in modules/packages 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.

Python also provides a wide array of external packages that can be integrated into your code.
5. Types of import statements
There are different import statements by which you can import Python modules/packages 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/packages using import
The import
statement followed by the module/package name is used to import the entire module/package into your Python code. You have access to all the variables, methods, and classes provided by the module/package.
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/packages using from import
The from import
statement allows you to import only the targeted variable, method, or class from the specified module/package.
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/package using import as
The import as
statement allows you to assign a new name to the module/package 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/packages using importlib
The importlib
module helps programmers to import modules/packages 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/package.
- 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/package.
- The
importlib
module is used when you want to import the modules/packages dynamically.
6. Handling module/package errors and exceptions
You might be facing some issues while importing modules/packages 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/packages.
Module not found error
This error occurs when you are trying to import a module/package that does not exist. Consider the following code block where we are trying to import a module/package 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.

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.

Error due to circular import
Another reason of getting Attribute error is circular imports. Consider the following code blocks.
Consider we have a file name module1.py
where we are importing a module module2
.
import module2
# function to add two numbers
def sum(a, b):
return a+b;
# calling sub function from module 2
module2.sub(9,4)
Consider another file named module2.py
in which we are importing a module module1
import module1
# function to subtract two numbers
def sub(a, b):
return a-b
# calling sum function from module 1
module1.sum(5,3)
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 following error.

In order to avoid the circular imports, you can import the modules in a separate file.
7. Best practices for importing modules/packages
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/packages that are required.
- Use aliases to give short and meaningful names to the imported modules/packages.
- Avoid circular imports by carefully organizing your code and dependencies.
- Use virtual environments to isolate the project dependencies.
Q. What is a module?
A. Modules are Python files e.g. module.py
that contain Python code.
Q. What is a package?
A. Packages are the directories that contains Python modules, it also contains a file init.py that indicate the directory is a package.
Q. How do you import modules/packages in Python?
A. You can import modules/packages using statements like 'import', 'from import', and 'import as' depending on your requirement.
Q. How can I install and use third-party modules/packages in Python?
A. You can install a third-party module/package 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/packages dynamically at runtime or under some conditions.
8. Conclusion
Modules and packages 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/packages in a specific way. You can dynamically import modules/packages using importlib. You can import third-party modules/packages using package managers like pip. We talked about the common errors that can occur while importing modules/packages like ModuleNotFound, AttributeError, and circular imports. Finally, we discussed best practices you can follow while importing the modules/packages.
9. References