views:

119

answers:

1

I'm pretty new to Python, and haven't been able to find an answer to this question from searching online.

Here is an example decorator that does nothing (yet)

def my_decorator(text):
  def wrap(f):
    # grab magic f.parent_class_object.my_var and append text
    def wrap_f(*args, **kwargs):
      f(*args, **kwargs)
    return wrap_f
  return wrap

Here is an example class

class MyClass:
  my_var = []

  @my_decorator('sometext')
  def my_func()
    # do some super cool thing

In my decorator i'd like to access the class object for MyClass and add in 'sometext' to the MyClass.my_var list. My goal is to populate my_var with decorated values at module load time, not function call time.

Is there a way i can navigate from f to MyClass in order to do this? I know that *args[0] is the instance of MyClass, but that is only available when the function is called.

+3  A: 

It is not possible to read it from a function inside a class decorator, since the "methods" are still normal function while the class is being compiled. Also, the class name has not been defined while it is being compiled.

What you could do is supply the my_var list to the decorator.

class MyClass:
    my_var = []

    @my_decorator(my_var, 'sometext')
    def my_func()
        # do some super cool thing

my_var is still a normal variable by then.

MizardX