Python Modules
0 128
Introduction to Python Modules
In Python, a module is essentially a file that contains Python code — it can include functions, classes, and variables. Modules help in organizing code logically, making it more readable and reusable. Think of a module as a tool that allows you to break down complex programs into smaller, manageable pieces.
Types of Modules in Python
Python modules can be broadly classified into three categories:
- Built-in Modules: These come pre-installed with Python. Examples include
math
,os
, andsys
. - User-defined Modules: Created by developers to use in their own programs. These are just Python files with reusable code.
- External Modules: Installed using package managers like pip. For instance,
numpy
andpandas
.
Creating a Module
Creating a module in Python is simple. Just write your code in a .py
file. Here's an example:
# greetings.py
def say_hello(name):
return f"Hello, {name}!"
Importing a Module
To use the functions defined in a module, you can import it in another Python file or directly in the interpreter. For example:
import greetings
print(greetings.say_hello("Alice"))
You can also import specific functions using:
from greetings import say_hello
print(say_hello("Bob"))
Renaming a Module During Import
You can give a custom name (alias) to a module when importing, which is useful for convenience or avoiding conflicts:
import greetings as gr
print(gr.say_hello("Charlie"))
Exploring Module Contents with dir()
To inspect what a module contains, you can use Python's built-in dir()
function:
import math
print(dir(math))
The __name__ Variable in Modules
Every Python module has a special built-in variable called __name__
. It helps determine whether the module is being run as a standalone script or being imported somewhere else.
# sample.py
print("Module Name:", __name__)
If you run sample.py
directly, the output will be:
Module Name: __main__
. But if you import it elsewhere, it will display the actual module name.
Conclusion
Python modules play a key role in writing clean and maintainable code. Whether you're using standard modules, creating your own, or leveraging third-party packages, mastering modules is essential for every Python developer.
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments