【发布时间】:2020-06-17 04:07:44
【问题描述】:
我正在尝试验证字典参数。
import logging
import os
# decorator
def file_validator(f):
def wrapped(*args):
"""
Once there is passed values,
file_path = os.path.join(path_info, file_info)
if os.path.exists(file_path):
logging.info('{} exists'.format(file_info))
else:
logging.info('{} does not exist'.format(file_info))
"""
# original function
@file_validator
def original_function(file_dict):
# pass only specific element to file_validator decorator for checking
# for example only "pathA": "/files", "fileA": "bar.csv"
sample_dict = {"pathA": "/files", "fileA": "bar.csv", "fileB": "hello.txt"}
original_function(sample_dict)
有没有办法使用装饰器检查这种方式?
编辑
这可能相当于我想要做的。
def file_validator(filepath, filename):
file_path = os.path.join(filepath + filename)
if os.path.exists(file_path):
logging.info('{} exists'.format(filename))
else:
logging.info('{} does not exist'.format(filename))
def original_function(file_dict):
file_validator(file_dict['pathA'], file_dict['fileA'])
file_validator(file_dict['pathA'], file_dict['fileB'])
sample_dict = {"pathA": "/files", "fileA": "bar.csv", "fileB": "hello.txt"}
original_function(sample_dict)
【问题讨论】:
-
@HArdRese7 我编辑了,因为我认为我的问题不清楚。我也检查了那个链接,但我觉得它没有太大关系??
-
您可以将您的 dict 作为输入传递给装饰器函数并实现您想要的。装饰器可用于修改函数行为,但不能用于修改传递给函数的参数。您可以使用这些类并实现相同的功能(如果您有兴趣,请查看 Django 的类级装饰器实现)