如何在 运行 时间将参数传递给装饰器?

How to pass parameters to decorators at run-time?

我正在使用装饰器进行一些上下文管理,例如文件备份、恢复项目中的排序,并尝试使用装饰器来实现该目的。

但我不明白如何在 运行 时将参数传递给装饰器。

例如我的 class 看起来像:

class myLogFileHandler:
    def __init__(self,file):
        self.file=file
        return

    @copyAndRestoreFile(file=<how-pass-self.file-here?>)
    def performAction(**kwargs):
        """
           do something
        """

我的装饰师是:

def copyAndRestoreFile(file):
    def dec(fn):
        def wrapper(*args,**kwargs):
            #copy file to temp...
            fn(*args,**kwargs)
            #restore file from temp...
        return wrapper
    return dec

但是如您所见,文件名只有在我创建对象时才可用。那么如何解决此类问题。

我尝试了几个有效的解决方案:

  1. 使装饰器不带任何参数,并使其在输入参数字典中查找特定变量..

    def copyAndRestoreFile(fn):
        def dec(**kwargs,file):
            #copy file to temp...
            fn(*args,**kwargs)
            #restore file from temp...
        return dec  
    
    @copyAndRestoreFile
    def performAction(**kwargs,file=self.file):
        """
           do something
        """
    

    使用这种方法,我无法使装饰器成为任何人都可以使用的通用装饰器。任何使用它的人都应该为被装饰的函数提供一个文件参数。这就是我的缺点看到...

  2. 在 运行 时间装饰..

    def performAction(**kwargs):
        copyAndRestoreFile(file=self.file)(self._actualActionCode)(**kwargs)
    
    def _actualActionCode(**kwargs):
        """
           do something
        """
    

有没有更好的方法来解决这个问题?

示例请看这里 - Passing parameters to decorator at runtime

如有其他细节请说明。