Introduction to Python Modules

introduction to python modules
10 November 2024

Modules are one of the powerful features of the Python programming language that provide better development and organization of code. Suppose you have a library of code that you want to use in different programs; modules are the best solution for you. By using modules, we can divide our codes into smaller sections and avoid repeating codes.

Each Python file that has the extension .py can be a module and can be used as a unit in different projects. For example, you might want to write code for mathematical operations that will be used in several different programs; by creating a module from this code, you can import it whenever needed.

Modules include predefined modules and also user-created modules. The standard library in Python provides various modules that can be used in many scenarios. For example, the math module is used for mathematical calculations, and the datetime module is used for working with dates and times, and they are among the most commonly used predefined modules.

In Python, importing a module is simply done using the keyword import along with the module name. You can import a complete module or just specific parts of a module. Moreover, users can create their own importable modules that enhance productivity for programmers.

Below is an example of how to create a simple module in Python and how to use it:


# Create the file my_module.py

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

# Using the module in another file
import my_module as mm

result_addition = mm.add(10, 5)
result_subtraction = mm.subtract(10, 5)
print("Addition:", result_addition)
print("Subtraction:", result_subtraction)

In the code above, I created a file named my_module.py, which includes two functions add and subtract.
Then, in another file, I imported the my_module module and named it as an alias mm for easier usage.
By using mm.add(10, 5) and mm.subtract(10, 5), addition and subtraction operations were performed, and their results were printed.

FAQ

?

How can I create a module in Python?

?

How can I import a Python module?

?

Can I import a specific part of a module?

?

Can I rename a Python module when importing it?