How to customize Python functions with decorators

Key takeaways:

  • A decorator is a function that wraps another function to enhance its behavior without changing its core functionality.

  • Decorators simplify tasks like validation, logging, and authentication, offering built-in functionalities.

  • The @property decorator allows methods to be used as attributes, while @<attribute>.setter adds custom logic for setting attribute values.

  • The @staticmethod decorator defines methods that can be called on the class itself, independent of instance data.

  • Custom decorators promote best practices by ensuring argument types match expected types, enhancing code reliability.

A decorator in Python is a function that wraps another function or method and helps to enhance its behavior. It is a valuable feature that dynamically alters the behavior of functions or methods by injecting some custom logic while maintaining their core functionality. It is commonly used for validation, logging, and authentication purposes.

Use cases

There are various instances where decorators provide us with ease through their built-in functionalities. In this Answer, we will explore a few such use cases.

@property and @<attribute>.setter decorators

The @property decorator helps to define a method as a getter for a class attribute. Later, it can be accessed as an attribute. This provides a clean way to implement read-only properties with custom logic. The @<attribute>.setter decorator in Python helps define custom logic for setting the value of a class attribute.

class Temperature:
def __init__(self, celsius):
# Initialize the temperature object with a given Celsius value
self._celsius = celsius
@property
def celsius(self):
# Getter method for the celsius attribute
print(f"Getting Temperature's state ")
return self._celsius
@celsius.setter
def celsius(self, value):
# Setter method for the celsius attribute
# Raises a ValueError if the provided value is below absolute zero
if value < -273.15:
raise ValueError("Temperature below absolute zero")
print(f"Setting Temperature's state to {value}")
self._celsius = value
@property
def fahrenheit(self):
# Getter method for the fahrenheit attribute
# Converts the Celsius value to Fahrenheit
return (self._celsius * 9/5) + 32
temp = Temperature(20) # Creating instance
get_temp = temp.celsius # Getting value of the celsius
temp.celsius = 10 # Setting celsius value

@staticmethod decorator

A static decorator, known as @staticmethod, defines methods within a class that don’t rely on instance-specific data, allowing them to be called on the class itself. Such methods provide utility functions related to the class, not to the instance state.

class FileUtils:
@staticmethod
def check_file_exists(filename):
# Static method to check if a file exists
try:
with open(filename, 'r') as file:
# If the file opens successfully, it exists
return True
except FileNotFoundError:
# If the file does not exist, a FileNotFoundError will be raised
return False
# Check if a file exists
# Call the static method using the class name, not an instance of the class
if FileUtils.check_file_exists("decorator.txt"):
print("The file exists.")
else:
print("The file does not exist.")

Custom decorator

Custom decorators are widely implemented to promote best coding practices. They can be applied to functions to ensure that the provided argument types match the expected types, enhancing code reliability and preventing type-related errors.

def validate(func):
# Define a decorator function to validate the argument type
def decorator(arg):
# Check if the argument is an integer
if not isinstance(arg, int):
# Print a message if the argument is not an integer and return None
print("Argument must be an integer")
return None
else:
# Call the original function if the argument is valid
return func(arg)
# Return the decorator function
return decorator
@validate
def cube(value):
# Return the cube of the input value
return value * value * value
result = cube(5) # Valid argument
print("Result:", result)
result = cube("5") # Invalid argument

Frequently asked questions

Haven’t found what you were looking for? Contact Us


Why do we need decorators in Python?

We need decorators in Python because they allow us to modify or extend function behavior without changing the original code.


Can decorators take arguments?

Yes, they can be designed to accept arguments.


Are decorators limited to functions only?

No, decorators can also be applied to classes.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved