Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

python - Access self objects and decorator parameters within a decorator

I have a decorator method within a class and I'm trying to add parameters for when the method is called e.g:

@log.diagnostic(DEBUG=True)
def exmp_function():
    '''
    Some stuff
    '''

Then, within the decorator I need to access both the parameters passed (e.g. DEBUG), as well as a number of self.attributes:

    def diagnostic(self,*args,**kwargs):
        self.DEBUG = args[0]
        def error_wrap(function): # DEBUG here isn't recognised
            @functools.wraps(function)
            def wrapper(*args,**kwargs):
                try:
                    result = function(*args,**kwargs)
                    self.status = 'OK'
                except Exception as error:
                    self.status = 'ERROR'
                    result = 'Error'
                finally:
                    self.to_File([self.file,self.status,self.DEBUG]) # self.file is defined outside
                    return result
            return wrapper
        return error_wrap

Currently, the self. attributes are correct, however, the decorator parameter is always the parameter of the last decorator to be called. I think this is because the outside wrapper is called for each decorator and then self.DEBUG is left as the last decorators parameter.

I therefore need to find a way to pass my DEBUG parameter down two layers. But I cannot find a way to do this.

Any help would be great thanks!

question from:https://stackoverflow.com/questions/65901238/access-self-objects-and-decorator-parameters-within-a-decorator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...