In Python, a module is a file containing Python code that can define functions, classes, variables, and executable code. Modules allow you to organize your Python code into reusable components and avoid code duplication. Here's an overview of modules in Python:
To create a module, you simply create a Python file with a .py extension and write your Python code inside it. The filename becomes the module name.
Example: my_module.py
# my_module.py
def greeting(name):
print("Hello, " + name + "!")
You can import a module into your Python script or interactive session using the import statement. After importing, you can access the functions, classes, and variables defined in the module using dot notation ( module_name.function_name ).
Example:
import my_module
my_module.greeting("Alice") # Output: Hello, Alice!
You can use an alias for a module name to simplify its usage, especially for modules with long names.
Example:
import my_module as mm
mm.greeting("Bob") # Output: Hello, Bob!
You can import specific functions, classes, or variables from a module rather than importing the entire module.
Example:
from my_module import greeting
greeting("Charlie") # Output: Hello, Charlie!
You can import all items from a module using the * wildcard. However, this is generally discouraged as it can lead to namespace pollution and make code harder to understand.
Example:
from my_module import *
greeting("David") # Output: Hello, David!
Python comes with a rich set of standard library modules that provide a wide range of functionality for common tasks. These modules include os, sys, math, random, datetime, json, re, and many others.
Example:
import random
print(random.randint(1, 100)) # Output: Random integer between 1 and 100
In addition to the standard library, Python has a vast ecosystem of third-party modules available for various purposes. You can install third-party modules using package managers like pip and then import them into your code.
When you import a module, Python searches for it in a specific order defined by the module search path ( sys.path ). The search path includes the current directory, directories specified by the PYTHONPATH environment variable, standard library directories, and site-specific directories.
Understanding modules and how to import and use them is essential for writing modular and maintainable Python code. Modules allow you to organize your code effectively, promote code reuse, and enable collaboration with other developers.