Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, decorator that wraps function with "with" statement

In Python 3.7+, is there a way to create a decorator that takes something like that:

@some_dec_fun
def fun():
    ...

And transforms and executes something like

def fun():
    with some_dec_fun():
        ...
like image 273
Aviel Fedida Avatar asked May 21 '26 05:05

Aviel Fedida


1 Answers

You can't use a decorator to 'get inside' another function. But you can use a decorator to execute the 'whole' decorated function within a particular context. For example the following will execute the function some_function within the context manager some_context_manager:

def my_decorator(func):
    def wrap():
      with some_context_manager():
          func()
    return wrap()

@my_decorator
def some_function:
  ...
like image 80
match Avatar answered May 23 '26 19:05

match