如何使此代码段更漂亮?

时间:2018-07-14 13:02:13

标签: python python-3.x loops

我正在寻找一种缩短此python3函数的方法。该函数需要很多输入变量,并检查每个变量是否为None。有没有一种方法可以遍历所有输入变量,并将不是None的变量添加到params字典中?

def news(self, query = None, instrument_id = None, days = None, news_lang = None, news_country = None, market_id = None, limit = None, offset = None, source_id = None):

    params = {}
    if query is not None:
        params['query'] = query
    if instrument_id is not None:
        params['instrument_id'] = instrument_id
    if news_lang is not None:
        params['news_lang'] = news_lang
    if news_country is not None:
        params['news_country'] = news_country
    if limit is not None:
        params['limit'] = limit
    if offset is not None:
        params['offset'] = offset
    if source_id is not None:
        params['source_id'] = source_id

    self.make_cmd('GET', 'news', params)

4 个答案:

答案 0 :(得分:4)

似乎所有参数都直接传递给make_cmd,所以为什么不使用关键字参数:

def news(self, **params):
    self.make_cmd('GET', 'news', params)

news(query="Test")

答案 1 :(得分:3)

我认为您正在定义方法而不是函数。以下将起作用:

def news(self, **kargs):
    params = kargs
    self.make_cmd('GET', 'news', params)

我想观察一下,您向方法传递了太多参数,这清楚地表明了称为Long Parameter List的编码。

答案 2 :(得分:2)

这能做得到吗?

import inspect

def news(self, query = None, instrument_id = None, days = None, news_lang = None, news_country = None, market_id = None, limit = None, offset = None, source_id = None):
    frame = inspect.currentframe()
    args, _, _, values = inspect.getargvalues(frame)

    params = {}

    for arg in args:
        if values[arg] is not None:
            params[arg] = values[arg]

    return params

print(news(1,2,3))

此解决方案的优点是您不需要使用允许任何参数名称的** kwargs或* args。

答案 3 :(得分:1)

如果这些参数的值不能为0,一个空列表或其他任何“虚假”的东西,则可以删除所有if检查:

params['query'] = query or None
.
.

或者,您可以简单地接受**params并将其传递给self.make_cmd

def news(self, **params):
    return self.make_cmd('GET', 'news', params)

此方法的缺点是,它的自我记录较少,最终用户将需要知道news接受的kwarg。