如何允许args和kwargs同时需要一个arg和kwarg;蟒蛇

时间:2016-03-10 20:37:02

标签: python python-2.7 python-2.x built-in

我有一个功能:

def get_results(datasource, attribute='all_results', *args, **kwargs):
    """gets results for basic datasource format"""
    print(args, kwargs)
    ds = datasource(*args, **kwargs)
    ds.get()
    results = getattr(ds, attribute)
    return results

称为

results = get_results(ThisDataSource, 'somestringID')

给出args / kwargs

(), {}

它的工作原理是

def get_results(datasource, *args, **kwargs):
    """gets results for basic datasource format"""
    print(args, kwargs)
    ds = datasource(*args, **kwargs)
    ds.get()
    results = ds.all_results()
    return results

给出args / kwargs

('somestringID',), {}

这种旧方法很糟糕,因为数据源可能想要返回行,列等 它的工作原理是

results = get_results(ThisDataSource, 'somestringID')

导致

ds = ThisDataSource('somestringID')

如何在声明中给它一个默认值,但仍然允许args和kwargs? 我想打电话

results = get_results(ThisDataSource, 'somestringID', attribute='rows') 

并拥有args = ('somestringID'), and retain access to attribute ='rows'`

谢谢

1 个答案:

答案 0 :(得分:2)

假设第一个位置参数为属性

    def get_results(datasource, *args, **kwargs):
        """gets results for basic datasource format"""
        attribute = 'all_results'  # default value
        if 'attribute' in kwargs:
            # attribure was given explicitly in keyword params
            attribute = kwargs['attribute']
        else:
            if len(args)>0:
                # args contains at least 1 value - we suppose first value to be an attribute
                # extract and remove it from args
                attribute = args.pop(0)
        print(attribute, args, kwargs)
        ...