python 装饰器没有从传递的常量中获取值

python decorators not taking the value from constant passed

report.py

if __name__ == "__main__":    
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description = "CHECK-ACCESS REPORTING.")
    parser.add_argument('--input','-i', help='Filepath containing the Active Directory userlist')
    parser.add_argument('--timestamp', '-t', nargs='?',const="BLANK", help='filepath with environement varible set')        
    args, unknownargs = parser.parse_known_args(sys.argv[1:])

    timestampchecker(args.timestamp)
    #checking the value of cons.DISPLAYRESULT is TRUE        
    main()

时间戳检查器函数:

def timestampchecker(status):
    """ Check if the timestamp is to display or not from command line"""
    if status is not None:
        cons.DISPLAY_TIME_STAMP = True

此函数检查用户是否设置了 -t 参数。如果它被设置,我已经定义了一个名为 cons.DISPLAYRESULT 的常量为真。

该函数运行良好,并将常量值变为 True。 但是在 main 函数中我实现了这个装饰器,它没有取真值而是假值

timer.py

def benchmarking(timestaus):
    def wrapper(funct):
        def timercheck(*args, **kwarg):
            if timestaus is True:
                starttime=time.time()
            funct(*args, **kwarg)
            if timestaus is True:
                print('Time Taken:',round(time.time()-starttime, 4))
        return timercheck
    return wrapper

我用上面的装饰器装饰了 report.py 的 main() 方法中的一些方法。例如,这是 class 在 report.py 中使用并用上面的装饰器装饰

class NotAccountedReport:

    def __init__(self, pluginoutputpath):
        """ Path where the plugins result are stored need these files"""

        self.pluginoutputpath = pluginoutputpath

    @benchmarking(cons.DISPLAY_TIME_STAMP)
    def makeNotAccountableReport():
        #some functionality

here I have passed the constant value to the argument decorator which when tested though before called is converted to True is taking false and thus the decorators not being implemented. Where is the problem cant figure out

你没有 post 一个完整的最小可验证示例,所以可能还有其他东西,但如果你的意思是在调用 NotAccountedReport().makeNotAccountableReport() 时你没有得到你的 "Time taken" 打印然后它真的不足为奇 - benchmarking 装饰器在函数定义时应用(当模块被导入时),远在 if __name__ == '__main__' 子句执行之前,所以那时 cons.DISPLAY_TIME_STAMP 尚未被您的命令行参数更新。

如果你想要运行时标志来激活/停用装饰器的行为,显而易见的解决方案是在装饰器中检查 cons.DISPLAY_TIME_STAMP 而不是将其作为参数传递,即:

def benchmarking(func):
    def timercheck(*args, **kwarg):
        if cons.DISPLAY_TIME_STAMP:
           starttime=time.time()
        result = func(*args, **kwarg)
        if cons.DISPLAY_TIME_STAMP:
            logger.debug('Time Taken: %s',round(time.time()-starttime, 4))
        return result  
    return timercheck


class NotAccountedReport(object):
    @benchmarking
    def makeNotAccountableReport():
        #some functionality