【问题标题】:pass kwargs and default values to ordered list将 kwargs 和默认值传递给有序列表
【发布时间】:2019-05-31 14:49:20
【问题描述】:

使用python 2.7,我一直在研究使用关键字参数来传递一个将新元组插入列表的函数。

我的目标:有一个函数接受一个必需的参数,然后将 n 个参数插入到特定位置的元组中,如果没有传递任何参数,则具有默认值。

这是我目前所拥有的:

def add_tagging_log_row(key, **time_stamp):
    tagging_log_rows.insert(len(tagging_log_rows), (key, time_stamp.get('is_processed'), time_stamp.get('is_processed')))



add_tagging_log_row('zzz', is_processed=datetime.datetime.now(), is_audited=datetime.datetime.now())

这是我正在构建的 tagging_low_rows 列表示例,其中填充了元组中的所有值:

[('key1', datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now()), ('key2', datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now())]

这里是列表中每个元组中项目的顺序:

key | is_processed | is_archived | is_error | is_audited

问题是在调用函数 add_tagging_log_row() 时,我总是会传递一个“键”,但在将其他时间戳字段插入到列表中时,可能会也可能不会将其他时间戳字段传递给元组。我需要这些字段为空字符串 ('')。

使用 **kwargs 是解决这个问题的正确方法吗?

【问题讨论】:

    标签: python-2.7 list tuples keyword-argument


    【解决方案1】:

    是的,使用kwargs 有效。不过,您需要在函数内部进行一些异常处理。 kwargs 作为字典传入。您可以检查字典中是否存在给定的时间戳,如果不存在则使用空字符串。尝试在函数内部做这样的事情:

    timestamps_order = ['is_processed', 'is_archived', 'is_error', 'is_audited']
    required_tuple = tuple([key] + [time_stamp[k] if k in time_stamp else "" for k in timestamps_order])
    

    附带说明 - 请考虑切换到 Python 3。Python 2.7 即将结束,未来不会获得任何支持。大多数图书馆已经停止支持它。

    【讨论】:

    • 感谢您的评论。我必须使用 python 2.7,因为 AWS 胶水环境不支持 python 3。
    猜你喜欢
    • 2015-01-28
    • 1970-01-01
    • 2010-12-31
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多