torsdag 4 augusti 2022

Decorators in Python

Decorator is a good name to describe what it does although the concept is a bit confusing at first. 

When a decorator has been made, it can potentially be used on any function you like. For example, you can extend/enhance your function to make it calculate how long it takes to run it.
All you have to do is adding "@your_decorator_name" just above the function you like to extend.
This means that additional code will be run, using your function in whatever way the decorator is defined to run it. And it uses the same arguments.

Example:


import functools

def your_decorator(base_func):
    @functools.wraps(base_func)
    # extended_func will be called instead of base func
    # since it's returned and replaces base func
    def extended_func(input_from_base_func):
        print("Printed inside the extended func")
        # This will call will_be_extended
        base_func(input_from_base_func)
        return "Returned when will_be_extended is called"
    return extended_func

@your_decorator
def will_be_extended(used_by_extension):
    # Do something
    print("Printed from base function")
    # This prints: "Sent to base func from decorator"
    print(used_by_extension)
   
# will_be_extended is called but the extended_func is returned
# automatically instead, including the text argument.
from_extended_func = will_be_extended("Sent to base func from decorator")

# This will print the returning value of extended_func,
# "Returned when will_be_extended is called"
print(from_extended_func)

 

Inga kommentarer:

Skicka en kommentar