如何将关键字对作为参数传递给函数中的模块?

How do I pass a keyword pair as an argument to a module in a function?

下面是一个搜索日期列表和 returns 指定日期出现次数的函数。我可以通过调用 zettel(1) 将天数传递给 relativedelta(days=x),但我也想传递一些年数(即 relativedelta(years=x))。

from datetime import date, datetime, timedelta
from dateutil.relativedelta import relativedelta

notelist = ['20211204', '20201205', '20191205', '20181205']


def zettel(x):
    ''' Returns the number of zettel created on this day 'x' years ago.'''
    note_uuid = datetime.now() - relativedelta(days=x)
    note_count = 0
    for uuid in notelist:
        if uuid == note_uuid.strftime('%Y%m%d'):
            note_count += 1
    return [x, note_count, note_uuid.strftime('%Y%m%d')]


print(f'[{zettel(1)[1]} new zettel yesterday.') 

print(zettel(1))

我试过传入 daysyears 和带有

的数字
    note_uuid = datetime.now() - relativedelta(y=x)

但是我明白了 NameError: name 'years' is not defined 当我调用函数时 print(f'[{zettel(years, 1)[1]})

我试过将整个参数 days=1year=1 传递给

    note_uuid = datetime.now() - relativedelta(x)

但是我明白了 TypeError: zettel() got an unexpected keyword argument 'years' 当我调用函数时 print(f'[{zettel(years=1)[1]})

如何将关键字“days”和“years”传递给函数relativedelta?这可能吗?

此代码有效,但我想对其进行扩展,以便计算不同的天数或年数。

您可以通过几种不同的方式实现这一目标。

选项一:直接传入“天”和“年”。调用示例:zettel(years=1).

def zettel(years=0, days=0):
    note_uuid = datetime.now() - relativedelta(years=years, days=days)
    ...

选项2:直接传递relativedelta。调用示例:zettel(relativedelta(years=1)).

def zettel(lookback):
    note_uuid = datetime.now() - lookback
    ...

选项 3: 传递关键字参数。调用示例:zettel(years=1).

def zettel(**lookback):
    note_uuid = datetime.now() - relativedelta(**lookback)
    ...