We need decorators in Python because they allow us to modify or extend function behavior without changing the original code.
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.
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
decoratorsThe @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 valueself._celsius = celsius@propertydef celsius(self):# Getter method for the celsius attributeprint(f"Getting Temperature's state ")return self._celsius@celsius.setterdef celsius(self, value):# Setter method for the celsius attribute# Raises a ValueError if the provided value is below absolute zeroif value < -273.15:raise ValueError("Temperature below absolute zero")print(f"Setting Temperature's state to {value}")self._celsius = value@propertydef fahrenheit(self):# Getter method for the fahrenheit attribute# Converts the Celsius value to Fahrenheitreturn (self._celsius * 9/5) + 32temp = Temperature(20) # Creating instanceget_temp = temp.celsius # Getting value of the celsiustemp.celsius = 10 # Setting celsius value
@staticmethod
decoratorA 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:@staticmethoddef check_file_exists(filename):# Static method to check if a file existstry:with open(filename, 'r') as file:# If the file opens successfully, it existsreturn Trueexcept FileNotFoundError:# If the file does not exist, a FileNotFoundError will be raisedreturn False# Check if a file exists# Call the static method using the class name, not an instance of the classif FileUtils.check_file_exists("decorator.txt"):print("The file exists.")else:print("The file does not exist.")
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 typedef decorator(arg):# Check if the argument is an integerif not isinstance(arg, int):# Print a message if the argument is not an integer and return Noneprint("Argument must be an integer")return Noneelse:# Call the original function if the argument is validreturn func(arg)# Return the decorator functionreturn decorator@validatedef cube(value):# Return the cube of the input valuereturn value * value * valueresult = cube(5) # Valid argumentprint("Result:", result)result = cube("5") # Invalid argument
Haven’t found what you were looking for? Contact Us
Free Resources