Aviel Fedida
Aviel Fedida

Reputation: 4102

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():
        ...

Upvotes: 2

Views: 981

Answers (2)

Corentin Pane
Corentin Pane

Reputation: 4943

To add on @match answer, if you need to pass the using resource as argument to your decorator, you can use the following code:

def using_dec(using_expr):
    def wrapper(func):
        def aux(*args, **kwargs):
            with using_expr():
                return func(*args, **kwargs)
        return aux
    return wrapper

and use it like this:

@using_dec(lambda : open("resource", 'w'))
def hello(x):
    print("hello " + str(x))

Upvotes: 3

match
match

Reputation: 11070

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:
  ...

Upvotes: 5

Related Questions