Python Modules
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py
. Modules allow you to organize your Python code logically and promote code reusability.
1. Creating a Module
To create a module, you simply create a Python file with the desired module name and define functions, classes, or variables in it.
Example: mymodule.py
def greet(name):
return f"Hello, {name}!"
2. Importing a Module
To use the definitions from a module in another Python script, you need to import the module using the import
statement.
Example: main.py
import mymodule
print(mymodule.greet("Alice")) # Output: Hello, Alice!
3. Importing Specific Items
You can import specific items (functions, classes, or variables) from a module using the from ... import ...
syntax.
Example:
from mymodule import greet
print(greet("Bob")) # Output: Hello, Bob!
4. Renaming a Module
You can rename a module when importing it using the as
keyword.
Example:
import mymodule as mm
print(mm.greet("Charlie")) # Output: Hello, Charlie!
5. Built-in Modules
Python comes with a set of built-in modules that provide various functionalities, such as math operations, file I/O, and datetime manipulation.
Example:
import math
print(math.sqrt(16)) # Output: 4.0
Conclusion
Modules are an essential part of Python programming, allowing you to organize and reuse code effectively. By understanding how to create, import, and use modules, you can build more modular and maintainable Python applications.