-2
I’ve done a lot of searching, but I can’t get where I think I can get.
Below I found these two possibility of decorators, I made a small modification for tests, see that inside the say_whee
i want to access quando
that’s inside the count_calls
, this is possible?
import functools
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func)
self.func = func
self.quando = None
def __call__(self, *args, **kwargs):
if args[0] == "segunda":
self.quando = "amanha"
return self.func(*args, **kwargs)
@CountCalls
def say_whee(dia):
print(CountCalls.quando)
say_whee("segunda")
import functools
def count_calls(func):
@functools.wraps(func)
def wrapper_count_calls(*args, **kwargs):
wrapper_count_calls.quando = None
if args[0] == "segunda":
wrapper_count_calls.quando = "amanha"
return func(*args, **kwargs)
return wrapper_count_calls
@count_calls
def say_whee(dia):
print(count_calls.quando)
say_whee("segunda")
It is possible, with important caveats, but the question is: why do you want to use decorator for this?
– Woss
Because this developer will be an access permit check. And in this check will have some extra vars for use within the function that used @Developer, I do not know if it was clear.
– Wellington Fonseca
It doesn’t really seem to be the best solution, mainly because the internal state of the decorator will be shared between the calls and this can bring negative consequences, especially if it is a validation of permissions. If you need to use these values in the function, why not pass them as parameters?
– Woss
In the
say_whee
you say?– Wellington Fonseca
Okay, I get it, in this case I should delete my question?
– Wellington Fonseca