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.pydef add( x , y ) :return x + ydef subtruct ( x , y ) :return x - y
Importing a Module :
Use the import keyword to bring functionality from a module into another Python script.
# main.pyimport math_operationsresult_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.pyfrom math_operations import add, subtructresult_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.