Modules in Python
Modules in Python are files containing Python code. This code can include functions, classes, or variables. A module can also include runnable code. You can use modules to organize your code into manageable sections and reuse code across different programs.
Creating a Module:
Creating a module is as simple as writing Python code in a file with a .py extension. For example:
# File: my_module.py
def greet(name):
return f"Hello, {name}!"
Importing a Module:
You can import a module into your code using the import
statement:
import my_module
print(my_module.greet("Alice")) # Output: Hello, Alice!
Using from...import
Statement:
You can import specific parts of a module using the from...import
statement:
from my_module import greet
print(greet("Bob")) # Output: Hello, Bob!
Exploring Module Contents:
You can explore the contents of a module using the dir()
function:
import my_module
print(dir(my_module)) # Lists all functions, classes, and variables defined in the module
You can also use the help()
function to get detailed information about the module:
help(my_module)
Using Built-in Modules:
Python comes with a rich set of built-in modules. For example, the math
module provides mathematical functions:
import math
print(math.sqrt(16)) # Output: 4.0
Best Practices for Using Modules:
- Module Naming: Use lowercase letters and underscores to name your modules (e.g.,
my_module
). - Organizing Code: Use modules to separate different functionalities within your project. For example, keep utility functions in one module and data processing functions in another.
- Reusability: Write reusable code in modules that can be easily imported and used in other projects.
Modules are a powerful feature in Python that helps you manage your code efficiently and promote reuse across different programs.
Import Links
Here are some useful import links for further reading: