Python modules are essential for organizing and reusing code. They allow developers to break down complex programs into manageable, reusable components.
A module is a file containing Python definitions and statements. It can define functions, classes, and variables that can be used in other Python programs.
To create a module, simply write Python code in a file with a .py
extension. For example:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return PI * self.radius ** 2
To use a module in another Python script, use the import
statement. There are several ways to import modules:
import mymodule
print(mymodule.greet("Alice"))
circle = mymodule.Circle(5)
print(circle.area())
from mymodule import greet, PI
print(greet("Bob"))
print(PI)
Python searches for modules in the following locations:
You can view the module search path using the sys.path
list from the Python sys Module.
When a Python file is run directly, its __name__
variable is set to '__main__'
. This allows you to include code that runs only when the file is executed as a script, not when it's imported as a module:
# mymodule.py
def some_function():
pass
if __name__ == '__main__':
print("This runs only when executed directly")
some_function()
To further enhance your understanding of Python modules, explore these related topics:
By mastering module creation and usage, you'll be able to write more organized, maintainable, and reusable Python code.