在python中如何将键值传递给decorator?

在python中如何将键值传递给decorator?,python,decorator,Python,Decorator,我正在尝试验证dictionary参数 导入日志 导入操作系统 #装饰师 def文件验证程序(f): def包装(*参数): """ 一旦传递了值, file\u path=os.path.join(路径信息,文件信息) 如果os.path.存在(文件路径): logging.info(“{}存在”。格式(文件\信息)) 其他: logging.info(“{}不存在”。格式(文件\信息)) """ #原函数 @文件校验器 def原始功能(文件目录): #仅将特定元素传递给文件\验证器装饰器进行

我正在尝试验证dictionary参数

导入日志
导入操作系统
#装饰师
def文件验证程序(f):
def包装(*参数):
"""
一旦传递了值,
file\u path=os.path.join(路径信息,文件信息)
如果os.path.存在(文件路径):
logging.info(“{}存在”。格式(文件\信息))
其他:
logging.info(“{}不存在”。格式(文件\信息))
"""
#原函数
@文件校验器
def原始功能(文件目录):
#仅将特定元素传递给文件\验证器装饰器进行检查
#例如,仅“pathA”:“/files”,“fileA”:“bar.csv”
示例_dict={“pathA”:“/files”,“fileA”:“bar.csv”,“fileB”:“hello.txt”}
原始函数(示例命令)
有没有办法使用decorator检查这种方式?
编辑 这可能相当于我想做的事情

def文件验证程序(文件路径,文件名):
file\u path=os.path.join(filepath+filename)
如果os.path.存在(文件路径):
logging.info(“{}存在”。格式(文件名))
其他:
logging.info({}不存在。格式(文件名))
def原始功能(文件目录):
文件验证程序(文件dict['pathA'],文件dict['fileA'])
文件验证程序(文件dict['pathA'],文件dict['fileB'])
示例_dict={“pathA”:“/files”,“fileA”:“bar.csv”,“fileB”:“hello.txt”}
原始函数(示例命令)

logging.info替换为此处打印以供验证

导入日志
导入操作系统
def文件验证程序(f):
def包装器(args):
对于路径,args.items()中的文件:
file\u path=os.path.join(路径,文件)
如果os.path.存在(文件路径):
打印({}存在。格式(文件路径))
其他:
打印({}不存在。格式(文件路径))
f(args)
返回包装器
@文件校验器
def原始功能(文件目录):
打印(文件目录)
示例_dict={“pathA”:“\\files”,“fileA”:“bar.csv”,“fileB”:“hello.txt”}
原始函数(示例命令)

看起来像这样的东西应该可以做到:

import os
import logging

def file_validator(func):
    def wrapper(file_dict:dict):
        
        # Turn file_dict to two lists:
        #   paths = ["/files"]
        #   files = ["bar.csv", "hello.txt"]
        paths = [
            path 
            for name, path in file_dict.items() 
            if name.startswith("path")
        ]
        files = [
            file 
            for name, file in file_dict.items() 
            if name.startswith("file")
        ]

        # Loop through all the path & file combinations and check if they exist
        for path in paths:
            for file in files:
               
                full_path = os.path.join(path, file)
                if os.path.exists(full_path):
                    logging.info('{} exists'.format(file))
                else:
                    logging.info('{} does not exist'.format(file))

        # Run the actual function
        return func(file_dict)
    return wrapper

@file_validator
def original_function(file_dict):
    ...

files = {"pathA": "/files", "fileA": "bar.csv", "fileB": "hello.txt"}
original_function(files) 
# Note that fileB is not checked as it's missing "pathB" 
# but from the question it is unclear how this should be handled 

但是有一些代码气味。如果可能的话,我建议不要以这种方式存储路径和文件,因为这样不容易操作,而且容易出现bug。更好的做法是将它们存储为完整路径列表,方法是使用
itertools.compositions
创建所有组合,或者只包含两个列表:路径和文件。

请查看。如果需要帮助,请让我们知道needed@HArdRese7我编辑,因为我觉得我的问题不清楚。我也检查了这个链接,但我觉得它没有多大关系??你可以将你的dict作为输入传递给decorator函数,实现你想要的。修饰符在修改函数行为时很有用,但在修改传递给函数的参数时却很有用。您可以使用这些类并实现相同的功能(如果您感兴趣,可以看看Django的类级装饰器实现)