I have a bunch of code:
statement1(args)
statement2(args)
statement3(args)
statement4(args)
statement5(args)
I want to divide the statements into blocks and write to a log after each block. The logging is a bit complex: I want to log things like the running time of each block and the state of a particular data structure after the block executes. So I created a decorator called log_block
which handles all of these details. Now my code looks like this:
@log_block()
def block1():
statement1(args)
statement2(args)
@log_block()
def block2()
statement3(args)
@log_block()
def block3():
statement4(args)
statement5(args)
block1()
block2()
block3()
This works just fine, but it's a little clunky. It's annoying that I have to separately call the three block functions, and if I want to share a variable between the blocks then I either have to give the block functions arguments and return statements or use global variables, neither of which is particularly palatable. What I really want is syntax which looks like this:
@log_block()
statement1(args)
statement2(args)
@log_block()
statement3(args)
@log_block()
statement4(args)
statement5(args)
so that I am decorating the statements directly rather than enclosing them in auxiliary block functions. Is there any way to achieve something like this?
To decorate a method in a class, first use the '@' symbol followed by the name of the decorator function. A decorator is simply a function that takes a function as an argument and returns yet another function.
A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
A decorator in Python is a function that takes another function as its argument, and returns yet another function . Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.
In fact, there are two types of decorators in Python — class decorators and function decorators — but I will focus on function decorators here.
Context managers are exactly what you are looking for. You use them with the with
statement, and they define code to be run on entering and exiting the with block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With