Robert_Jordan
Robert_Jordan

Reputation: 266

Access to attributes of Class-based decorators with arguments

Lets say I have a class based-decorator with an argument like this:

class Decorator:
    def __init__(self, arg):
        self.arg = arg

    def __call__(self, func):
        def wrap():
            # something with self.arg
            func()
        return wrap

When I have a decorated function foo, I can do following:

deco = Decorator("ARG")
def foo():
    pass
foo = deco(foo)
deco.arg = "CHANGE ARG"

It is possible to access/change deco.arg in some way, if I go with the @-Syntax?

@Decorator("ARG")
def foo():
    pass

# How to change/access the arg-attribute?

Upvotes: 2

Views: 284

Answers (1)

MSeifert
MSeifert

Reputation: 152647

You could create a closure:

def Decorator(arg):
    class InnerDecorator:
        def __init__(self, func):
            self.func = func
            # make arg an instance attribute
            self.arg = arg  

        def __call__(self):
            return self.func()

    return InnerDecorator

@Decorator("ARG")
def foo():
    pass

And then set the attribute on the function:

>>> foo.arg
'ARG'
>>> foo.arg = 'WOW'
>>> foo.arg
'WOW'

Upvotes: 2

Related Questions