Как передать ключ-значение декоратору в python? - PullRequest
0 голосов
/ 17 июня 2020

Я пытаюсь проверить параметр словаря.

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)

1 Ответ

0 голосов
/ 17 июня 2020

logging.info заменяется здесь печатью для проверки.

import logging
import os

def file_validator(f):
    def wrapper(args):
        for path, file in args.items():
            file_path = os.path.join(path, file)
            if os.path.exists(file_path):
                print('{} exists'.format(file_path))
            else:
                print('{} does not exist'.format(file_path))
        f(args)
    return wrapper


@file_validator
def original_function(file_dict):
    print(file_dict)

sample_dict = {"pathA": "\\files", "fileA": "bar.csv", "fileB": "hello.txt"}
original_function(sample_dict)
...