Accessing a variable from a developer

Asked

Viewed 24 times

-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")
  • 2

    It is possible, with important caveats, but the question is: why do you want to use decorator for this?

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

  • 2

    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?

  • In the say_whee you say?

  • Okay, I get it, in this case I should delete my question?

1 answer

0

I was able to find the answer to my question, but before we get there stay tuned. My need was to use the decorator to validate an access and consume some variables through this decorator, as directed me, nay is recommended for such use.

So, before using think very carefully for what purpose will be used, so you have no problems

def funcDec(func):
    def wrapped(x, y):
        print(x)
        print(y)

        localVariable = "DOIS"
        # print(localVariable)
        funcDec.attrib = localVariable

        func(x, y)
        print("done with calling f1")

    return wrapped

@funcDec
def f1(x, y):
    print(x + y)
    print(funcDec.attrib)

f1(2, 3)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.