Using Modules and Packages with Python


In the Python programming language, modules and packages allow your code to be more organized and reusable. Modules are Python files and generally represent pieces of code grouped together with similar functionalities. Packages, on the other hand, are directories containing multiple modules. In this article, we will discuss using modules and packages with Python.

What is a Module?

A module is a structure that allows Python code to be organized in a file. For example, when we create a file called math.py, we can define mathematical functions and constants in it. We use the import keyword to use modules. Below you can see a simple module example:

# math_operations.py

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

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

Using a Module

To use this module we created in another Python file, we can import it as follows:

# main.py
import math_operations

sonuc = math_operations.toplama(5, 3)
print(f'Result: {sonuc}')  # Result: 8

What is a Package?

A package is a directory that brings together multiple modules. In Python packages, there must be an __init__.py file. This file allows Python to recognize the directory as a package. An example package directory is given below:

my_package/
    ├── __init__.py
    ├── math_operations.py
    └── string_operations.py

Using a Package

To use modules inside a package, we follow a structure like the one below:

# main.py
from my_package import math_operations

sonuc = math_operations.toplama(5, 3)
print(f'Result: {sonuc}')  # Result: 8

Conclusion

Using modules and packages with Python helps the developer make their code more organized and clean. Modules gather code groups that perform a specific function together, and packages allow us to organize these modules. By using modules and packages in Python, we can make our projects more manageable.