添加日期的装饰器的断言错误

问题描述 投票:0回答:1

我应该编写装饰器,该装饰器将给定日期格式的日期添加到函数返回的字典的参数中。这是我的代码:

import datetime  # do not change this import, use datetime.datetime.now() to get date


def add_date(format):
    def decorator(f):
        def inner(*args):
            dic=dict(f(*args))
            dic['date']=datetime.datetime.now().strftime(format)
            return dic
        return inner
    return decorator

@add_date('%B %Y')
def get_data(a=5):
    return {1: a, 'name': 'Jan'}

assert get_data(2) == {

    1: 2, 'name': 'Jan', 'date': 'April 2020'

}

但是运行强制性测试后,由于警报我没有通过测试:

Traceback (most recent call last):
  File "/home/runner/unit_tests.py", line 64, in test_add_date
    self.assertEqual(get_data(a=5), {
TypeError: inner() got an unexpected keyword argument 'a'

而且我也不知道如何解决它。有什么建议吗?

python python-decorators
1个回答
0
投票

您正在将5作为keyword自变量(a=5)传递,但是inner函数仅接受positional自变量(*args)。使其像这样接受关键字参数(**kwargs)将解决您的问题

def inner(*args, **kwargs):
    dic = dict(f(*args, **kwargs))
    dic['date']=datetime.datetime.now().strftime(format)
    return dic

Check Python documentation for more information on positional and keyword arguments.

© www.soinside.com 2019 - 2024. All rights reserved.