0

I have this decorator which takes one argument by itself before it decorates a provided function.

That decorator is then used to decorate a class method. Let's say we have the following code:

from somewhere import dec

class Something:
    def __init__(self, variable = 5):
        self.variable = variable

    @dec(need_to_access_instance_self_variable)
    def some_method(self, blahblah):
        # does something
        pass

Everything works like a charm, except I'd like to pass self.variable as an argument to the decorator—and nothing hasn't worked for me so far.

Is this even possible? I cannot seem to figure out the scoping. Any ideas how would that be achievable?

Thank you!

Radek Kysely
  • 100
  • 1
  • 7
  • 1
    `self` does not exist there, so that isn't workable. Your decorator implementation can make use of the first-argument passed to the function it is decorating, maybe – juanpa.arrivillaga Dec 05 '17 at 00:00
  • 1
    `self` is a reference to the instance the method is being called on. At decoration time, there is no instance and therefore no `self`. – kindall Dec 05 '17 at 00:01
  • 1
    Note, `self` in Python is *way* more straight-forward than `this` in java-script, it is simply the first argument passed to the method, and when a method is accessed by an instance, it will auto-magically (through descriptors) be provided the instance accessing the method as the first argument. Indeed, it isn't the name `self` that has any special status, that is merely a convention, you *could* use `this` or `that` or `banana`, but what is important is that it is the *first* argument to a method. – juanpa.arrivillaga Dec 05 '17 at 00:08
  • IOW, you could think of `my_instance.some_method(arg1, arg2)` as being syntactic-sugar for `MyClass.my_method(my_instance, arg1, arg2)` – juanpa.arrivillaga Dec 05 '17 at 00:09
  • @juanpa.arrivillaga Yeah, accessing it from within decorated at runtime is a good idea :) Thank you – Radek Kysely Dec 05 '17 at 00:17

0 Answers0