Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to directly "decorate" a block of Python code?

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?

like image 404
Paul Siegel Avatar asked Jul 18 '16 14:07

Paul Siegel


People also ask

How do you decorate a Python method?

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.

What can be decorated in Python?

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.

How does decorators work in Python?

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.

How many decorators are there in Python?

In fact, there are two types of decorators in Python — class decorators and function decorators — but I will focus on function decorators here.


1 Answers

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.

like image 142
Daniel Roseman Avatar answered Nov 01 '22 20:11

Daniel Roseman