定义一个函数,
MyFunction(argument, *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 的长度,并且在迭代开始之前我无法访问源中 item 的键......
所以,我可以
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)