You are currently viewing Creating modules and packages
Python | Creating modules & packages

Creating modules and packages

To create a module in Python, you just need to create a new .py file with the name of the module you want to create. In this file, you can define the functions, classes, and variables you want to include in the module.

For example, let’s create a module called math_operations.py that includes functions for basic math operations:
# math_operations.py

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    return a / b

To use this module in another Python script, you can import it using the import keyword:

import math_operations

print(math_operations.add(5, 3))
print(math_operations.subtract(5, 3))
print(math_operations.multiply(5, 3))
print(math_operations.divide(5, 3))

This will output:

8
2
15
1.6666666666666667

You can also import specific functions or variables from a module using the from keyword:

from math_operations import add, subtract

print(add(5, 3))
print(subtract(5, 3))

This will output:

8
2

To create a package, you need to create a folder with the name of the package you want to create. Inside this folder, you can include one or more Python modules.

For example, let’s create a package called my_package that includes the math_operations module we created earlier:

my_package/
    __init__.py
    math_operations.py

The __init__.py file is required to make the folder a package. It can be an empty file, or it can include some initialization code.

To use the math_operations module from the my_package package, you can import it like this:

from my_package import math_operations

print(math_operations.add(5, 3))
print(math_operations.subtract(5, 3))

This will output:

8
2

Leave a Reply