在函数中允许任意数量的参数?

时间:2017-09-13 16:05:07

标签: python

修改此功能的最佳方法是什么,以允许多个过滤器'? ' filter_column'参数可以是一个或多个值。每个值都需要传递给request.filters参数。

def create_data_policy(dataset_id, filter_column, filter_value, user_id):
    filter = PolicyFilter()
    filter.column = filter_column
    filter.operator = FilterOperator.EQUALS
    filter.values = [filter_value]
    request = Policy()
    request.filters = [filter]
    request.name = f'Filter | {filter_value}'
    request.type = PolicyType.USER
    request.users = [user_id]

如果我定义单个filter_columnfilter_values

列表,此功能可以正常工作
create_data_policy(dataset_id=123, filter_column='employee_name', filter_value='Jane', user_id='1243')

如果我想创建多个过滤器怎么办? request.filters接受潜在过滤器列表。

request.filters = [filter1, filter2, filter3]

编辑 - 这是我使用kwargs实现的解决方案。如何循环键,值并将它们附加到列表中是否有意义?

def test_func(dataset_id, **kwargs):
    final_pdp = []
    for key, value in kwargs.items():
        pdp_filter = f'{key}_filter'
        pdp_filter = PolicyFilter()
        pdp_filter.column = key
        pdp_filter.operator = FilterOperator.EQUALS
        pdp_filter.values = [f'{key}: {value}']
        pdp_filter.values = value
        final_pdp.append(pdp_filter)
    pdp_request = Policy()
    pdp_request.filters = final_pdp
    pdp_request.type = PolicyType.USER
    pdp = create_pdp(dataset_id, pdp_request)
    print(f"Created a Personalized Data Policy (PDP): {pdp['id']}")

test_func(dataset_id='test', project=['Test'], location=['NY'])

2 个答案:

答案 0 :(得分:1)

尝试使用*args**kwargs

>>> def f(*args):
...     print(args)
...
>>> f(1, 2, 3, 4)
(1, 2, 3, 4)

>>> def f(**kwargs):
...     print(kwargs)
...
>>> f(a=1, b=2, c=3)
{'a': 1, 'b': 2, 'c': 3}

答案 1 :(得分:1)

你考虑过字典吗? Yo可以传递一个字典,其中列名称为键,过滤器列表为值。