In Python, a Module is a file containing Python definitions and statements.
The file name is the module name with the suffix ".py".
Modules can define "functions", "classes", and "variables". Using modules allows us to organize code, improve readability, and facilitate code reuse.
Modular programming is the practice of splitting a source code into smaller modules it helps us to manage sub-modules easily. We can build a larger and more complex program by assembling sub-modules that act like building blocks.
Reusability: Functions created in a specific module can be accessed by different sections of the assignment. As a result, it prevents writing duplicate code.
Simplification: A module will concentrate on one sub-task of the overall problem instead of the full task. We will have a more manageable code design. Program development is now simpler and much less vulnerable to mistakes.
To create a module, we simply create a new Python file with a ".py" extension.
create a file named "custom_module.py".
# custom_module.py def greeting(name): print("Hello, " + name) person = { "name": "Alice", "age": 23, "country": "England" } class YourClass: def __init__(self, x): self.x = x def square(self): return self.x * self.x
Once we have created a module, we can use it in other Python scripts by importing it. There are a few different ways to import modules:
# import entire import custom_module # import specific items from module from custom_module import greetMethod, userDetailsVariable, EmployeeClass # import entire module as Alias import custom_module as CM
# current file name main.py file # import entire custom_module from custom_module.py file import custom_module custom_module.greeting("Alice") # Output: Hello, Alice print(custom_module.person) # Output: {'name': 'Alice', 'age': 23, 'country': 'England'} obj = custom_module.YourClass(10) print(obj.square()) # 100
from custom_module import greeting, person greeting("Clark") # Output: Hello, Clark print(person) # Output: {'name': 'Alice', 'age': 23, 'country': 'England'}
import custom_module as ym ym.greeting("Harry") # Output: Hello, Harry print(ym.person) # Output: {'name': 'Alice', 'age': 23, 'country': 'England'}
Python comes with a standard library that provides a wide range of modules for various purposes.
We can use these modules by importing them into our code.
Some common standard library modules include os, sys, math, random, datetime, json, and many more.
import os current_directory = os.getcwd() print("Current directory:", current_directory)
In Python, Modules are a fundamental concept that enables flexibility, reusability, code organization, and maintainability.
By importing built-in and custom modules, we can access a wide range of functionalities and streamline while development process.