什么是创建一个集合时处理空* args的pythonic方法?

时间:2010-11-29 05:00:55

标签: python function arguments default function-signature

定义一个函数,

MyFunction(参数,* args): [为* args中的arg参数[arg]做点什么]

如果* args为空,则该函数不执行任何操作,但我想使默认行为'如果长度为* args == 0'则使用整个集合

def Export(source, target, *args, sep=','):
    for item in source:
        SubsetOutput(WriteFlatFile(target), args).send(item[0])

我不想在每次迭代时检查args的长度,而且我无法访问其中的键 源代码直到迭代开始......

所以我可以

if len(args) != 0:
   for item in source:

else
   for item in source:

这可能会起作用,但看起来不像'pythonic'吗?

这是(有)标准的方法来处理* args或** kwargs和默认行为,当其中任何一个为空时?

更多代码:

def __coroutine(func):
    """
    a decorator for coroutines to automatically prime the routine
    code and method from 'curous course on coroutines and concurrency'
    by david beazley www.dabeaz.com
    """

    def __start(*args, **kwargs):
        cr = func(*args, **kwargs)
        next(cr)
        return cr
    return __start


def Export(source, target, *args, sep=','):
    if args:
        for item in source:
            SubsetOutput(WriteFlatFile(target, sep), args).send(item)
    else:
        for item in source:
            WriteFlatFile(target, sep).send(item)

@__coroutine
def SubsetOutput(target, *args):
    """
    take *args from the results and pass to target

    TODO
    ----
    raise exception when arg is not in result[0]
    """
    while True:
        result = (yield)
        print([result.arg for arg in result.dict() if arg in args])
        target.send([result.arg for arg in result.dict if arg in args])


@__coroutine
def WriteFlatFile(target, sep):
    """
    take set of results to a flat file

    TODO
    ----
    """
    filehandler = open(target, 'a')
    while True:
        result = (yield)
        line = (sep.join([str(result[var]) for
                        var in result.keys()])).format(result)+'\n'
        filehandler.write(line)

3 个答案:

答案 0 :(得分:4)

有没有办法将“整个集合”参数传递给SubsetOutput,这样你就可以将条件埋在其调用中而不是明确if?例如,这可以是None[]

# Pass None to use full subset.
def Export(source, target, *args, sep=','):
    for item in source:
        SubsetOutput(WriteFlatFile(target), args or None).send(item[0])

# Pass an empty list [] to use full subset. Even simpler.
def Export(source, target, *args, sep=','):
    for item in source:
        SubsetOutput(WriteFlatFile(target), args).send(item[0])

如果没有,我会选择两个循环解决方案,假设循环真的是单行。它读得很好,是一个合理的用例,可以进行一些代码重复。

def Export(source, target, *args, sep=','):
    if args:
        for item in source:
            SubsetOutput(WriteFlatFile(target), args).send(item[0])
    else:
        for item in source:
            FullOutput(WriteFlatFile(target)).send(item[0])

答案 1 :(得分:1)

这个怎么样:

def MyFunc(argument, *args):
    ( DoSomething for i in (filter(args.__contains__ ,argument) if args else argument) )

答案 2 :(得分:0)

只检查它不是没有,你不必创建一个单独的参数

def test(*args):
    if not args:
        return #break out
    return True #or whatever you want