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

2024-04-26 20:38:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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'

我也不知道如何修复它。有什么建议吗


Tags: importaddformatdatagetdatetimedatereturn
1条回答
网友
1楼 · 发布于 2024-04-26 20:38:56

您正在将5作为关键字参数(a=5)传递,但是inner函数只接受位置参数(*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.

相关问题 更多 >