A decorator is a function that modifies the output of the function it is applied to. In Python, you deploy a decorator using the @
symbol followed by the decorator name.
@decorator_name
def func_name:
...
The above code is the syntax for deploying a decorator in Python. Decorators make it easy to modify a function without changing the function's source code. It provides a concise way to extend a function's functionality. Python has some decorators built-in decorators; here are some of them.
@atexit.register
This decorator is used to run a function at program termination.
import atexit
@atexit.register
def on_exit():
# Clean up tasks
print('Exiting program...')
def main():
print('Program running')
# Program logic
if __name__ == "__main__":
main()
Output
Program running
Exiting program...
@dataclass
The dataclass
decorator is used to generate special methods for classes. It eliminates the need to write boilerplate code for initialization and instance comparisons.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
# Print object
point = Point(x=3, y=2)
print(point)
# Compare objects
print(Point(x=1, y=2) == Point(x=1, y=2))
Output
Point(x=3, y=2)
True
@unique
This is found in the enum module, and it is used to ensure all values in the Enum class are unique. It prevents the accidental creation of multiple enum values that are unique. If duplicates are found, a ValueError
is raised.
from enum import Enum, unique
try:
@unique
class Level(Enum):
ONE = 1
TWO = 2
THREE = 3
FOUR = 3
except ValueError as e:
print(e)
Output
Error: duplicate values found in <enum 'Level'>: FOUR -> THREE
You can also create your own decorator for your own specific purposes. Let's build a simple decorator that modifies the output of a function.
def count_chars(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return f'output: {result} | modified: {len(result)}'
return wrapper
@count_chars
def say_hello(name):
return f'Hello, {name}'
print(say_hello('Jane'))
Output
output: Hello, Jane | modified: 11
In the example above, the decorator takes the output of say_hello
and returns the number of characters in the string as the modified output.
Decorators are very easy to understand, and even beginners can start using them to enhance their Python code. You can either create one or take advantage of the built-in decorators in Python.