In this article we want to learn How to Create Modules in Python 3, first of all let’s talk that What are Python Modules?
What are Python Modules ?
Module in Python is file that contains definitions, functions, classes and statements that can be reused in multiple programs. Module provides a way to structure and organize your code, and after that it will easy to maintain and reuse the code.
Structure of Python Modules
Each module in Python has unique name, and you can import that into another Python program using import statement. after that the imported module acts as namespace, and you can access its functions, classes and variables using dot notation (like module_name.function_name).
for example, you could have module named “math_functions.py” that contains different mathematical functions, and after that you import that module into another code to use its functions. this allows you to write reusable and modular code that can be easily shared and maintained.
Python Built-in Modules
In addition to user defined modules, Python also have different built in modules, and these built-in modules provide common functionality, for example the math module is for mathematical operations, os module is for interacting with the operating system, and json module is for working with JSON data.
How to Create Modules in Python 3?
So now let’s talk about creating modules in Python.
These are the steps to create module in Python 3:
- Choose a file name for your module and save it with .py extension. for example, you can name your module my_module.py.
- Define functions, classes and variables inside the file. for example:
1 2 3 4 5 6 7 |
def my_function(arg1, arg2): # code here class MyClass: # code here my_variable = "Hello World" |
For using this module in another code, you can use import statement followed by the name of the module:
1 2 3 |
import my_module result = my_module.my_function(1, 2) |
Note: You can also import specific objects from the module using from statement:
1 2 3 |
from my_module import my_function result = my_function(1, 2) |
This way, you can use the imported objects directly in your script without having to qualify them with the name of the module.
Subscribe and Get Free Video Courses & Articles in your Email