Search code examples
pythondecoratorpython-decorators

python: class namespace for simple decorator function


I am somewhat new to decorators in Python and are struggeling with a simple decorator, that is supposed to check for a state of my class (doing the operation once when one of the dependending functions is actually called for the first time). My problem is, that I want to let the decorator function also know about everything in self and pass the actual function as 'argument'(?)

class myClass(object):
    __init__(self):
        self.__isFoo = False
        self.__baz = 0

    def doFoo(self):
        ...  
        self.__isFoo = True

    def fooInit(self,func):
        if not self.__isFoo:
            self.doFoo()
        return func

    @property
    @fooInit
    def getBaz(self):
        return self.__baz

however, with this one, I get an error that

myObj = myClass()
myObj.getBaz

~~> TypeError: fooInit() takes exactly 2 arguments (1 given)

which I somewhat understand, since it is just self.fooinit( self.getBaz ) if I understand decorators correctly, or?

So I am a bit lost now, how I can define the decorator in an easy way, that it also knows the other objects in the class namespace?


Solution

  • following @aruisdante's suggestions I managed to get a proper decorator working

    def fooInit(func):
        def _wrapped(self,*args, **kwargs):
            if not self.__isFoo:
                self.fooInit()
                return func(self,*args, **kwargs)
        return _wrapped
    

    (defined within my class)