Python - Modules

01-Feb-2024

Explore the concept of modules in Python. Learn how to organize your code into modular units, create your own modules, and leverage existing modules to enhance code reusability.

Introduction

A file with Python definitions and statements inside of it is called a module. With '.py' suffix, the file name is the module name. With the use of modules, related code can be arranged into distinct files for easier reuse and maintenance.


Creating a Module :

Create a Python file with a .py extension and define functions or variables inside it.


# math_operations.py
def add( x , y ) :
return x + y

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



Importing a Module :

Use the import keyword to bring functionality from a module into another Python script.


# main.py


import math_operations

result_add = math_operations.add(3 , 4 )
result_sub = math_operations.subtruct(8 , 5 )

print('Addition ' , result_add)
print('Subtruction ' , result_sub)



Importing Specific Functions:


You can import specific functions from a module to use them directly.


# main.py

from math_operations import add, subtruct

result_add = add(3 , 4 )
result_sub = subtruct(8 , 5 )

print('Addition ' , result_add)
print('Subtruction ' , result_sub)




Notes


- Code may be better structured by using modules to divide it up into distinct files.
- The importing script gains access to a module's variables and functions upon import.
- For more focused use, specific functions can be imported from a module.



Conclusion

Better code reuse and structure are made possible by knowing how to construct and use Python modules. Using modules improves maintainability and teamwork whether working on small projects or huge codebases.

Comments