Skip to content

Decorators

Decorators allow to modify a function or a class method in python without modifying they actual code

# Function Copy
def hello():
    return "Hello World!"


print(hello)
print(hello())

hello_copy = hello
print(hello_copy)
print(hello_copy())

del hello
print(hello_copy)

Hello World!

Hello World!

1
2
3
4
5
6
7
8
9
# Closures
def outer_function(msg):
    def inner_function():
        return msg

    return inner_function()


outer_function("Hello, World!")

'Hello, World!'

## Decorator


def decorator_function(original_function: callable):
    def wrapper_function():
        print("Something is happening before the original function is called.")
        original_function()
        print("Something is happening after the original function is called.")

    return wrapper_function


@decorator_function
def display():
    print("Display function executed")


display()

Something is happening before the original function is called.

Display function executed

Something is happening after the original function is called.

## Decorator with arguments
def repeat(num_times: int):
    def decorator_repeat(original_function: callable):
        def wrapper_function(*args, **kwargs):
            for _ in range(num_times):
                original_function(*args, **kwargs)

        return wrapper_function

    return decorator_repeat


@repeat(num_times=3)
def greet(name: str):
    print(f"Hello, {name}!")


greet("Alice")

Hello, Alice!

Hello, Alice!

Hello, Alice!