site logo

Learn to Python. Build the Future.


Category: (All)
❮  Go Back

18. Mastering Python Functions and Decorators

Introduction

In Python, functions are fundamental building blocks that allow you to encapsulate code into reusable units. Decorators, introduced in Python 2.4, are a powerful feature that enables you to modify or enhance functions or methods without changing their actual code. Understanding both concepts is essential for writing clean, efficient, and maintainable Python code.


Python Functions

Defining a Function

Functions in Python are defined using the def keyword, followed by the function name and parentheses containing any parameters. The function body starts with a colon and is indented.

Example:

def greet(name):
print(f"Hello, {name}!")

Calling a Function

To execute the function, you call it by its name and pass the required arguments.

Example:

greet("Alice")

Output:

Hello, Alice!

Function Arguments

Functions can accept parameters, which are values passed into the function. You can specify default values, use variable-length arguments, and more.

Example:

def add(a, b=5):
return a + b

Calling the function:

print(add(3)) # Output: 8
print(add(3, 4)) # Output: 7

Return Values

Functions can return values using the return statement. Once a return statement is executed, the function terminates.

Example:

def multiply(x, y):
return x * y

Calling the function:

result = multiply(4, 5)
print(result) # Output: 20


Python Decorators

A decorator is a function that takes another function as an argument, adds some functionality, and returns a new function. They are commonly used to modify the behavior of functions or methods.

Basic Decorator

Example:

def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper

@decorator
def say_hello():
print("Hello!")

Calling the decorated function:

say_hello()

Output:

Before function call
Hello!
After function call

Using functools.wraps

To preserve the metadata of the original function, such as its name and docstring, you can use functools.wraps in your decorator.

Example:

from functools import wraps

def decorator(func):
@wraps(func)
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper


Conclusion

Understanding functions and decorators in Python allows you to write more modular and reusable code. Functions help encapsulate logic, while decorators provide a way to modify or extend that logic without altering the original function's code. By mastering these concepts, you can enhance the readability and maintainability of your Python programs.

18. Mastering Python Functions and Decorators

coldshadow44 on 2025-10-08



(0)





Showing comments related to this post.




Member's Sites: