[Python] How can I use decorators to modify the behavior of multiple functions in Python?

Discussão em 'Python' iniciado por Stack, Setembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    I’m learning about decorators in Python and would like to use them to modify the behaviour of several more complex functions in my code. Specifically, I want to:

    • Log the execution time for each function.
    • Handle and log any errors that occur during function execution.

    Here's an example of one of my functions, which processes a list of numbers, filters out the even numbers, and computes the sum of the remaining odd numbers:

    def my_function(numbers):
    odd_numbers = [n for n in numbers if n % 2 != 0]
    result = sum(odd_numbers)
    return result


    I also have another function that processes a string by reversing the words in the sentence:

    def reverse_sentence(sentence):
    words = sentence.split()
    reversed_sentence = ' '.join(reversed(words))
    return reversed_sentence


    I understand how to create a simple decorator, but how do I create a decorator that:

    • Logs the execution time of each function.
    • Catches and logs any errors that occur during function execution.

    I would like to apply this decorator to both of these functions (and potentially others). Any help with an example would be greatly appreciated!

    Continue reading...

Compartilhe esta Página