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