jus*_*ess 6 python arguments default function function-signature
定义一个函数,
MyFunction(argument, *args): [为*args 中的arg 对argument[arg] 做一些事情]
如果 *args 为空,则该函数不执行任何操作,但我想设置默认行为“如果 *args == 0 的长度则使用整个集合”
def Export(source, target, *args, sep=','):
for item in source:
SubsetOutput(WriteFlatFile(target), args).send(item[0])
Run Code Online (Sandbox Code Playgroud)
我不想在每次迭代中检查 args 的长度,并且在迭代开始之前我无法访问源中 item 的键......
所以,我可以
if len(args) != 0:
for item in source:
else
for item in source:
Run Code Online (Sandbox Code Playgroud)
这可能会起作用,但似乎不够“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)
Run Code Online (Sandbox Code Playgroud)
只需检查它不是 none,您不必创建单独的参数
def test(*args):
if not args:
return #break out
return True #or whatever you want
Run Code Online (Sandbox Code Playgroud)
有没有办法将“整个集合”参数传递给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])
Run Code Online (Sandbox Code Playgroud)
如果没有,我会采用两个循环解决方案,假设循环确实是一条线。它读起来很好,并且是一些代码重复的合理用例。
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])
Run Code Online (Sandbox Code Playgroud)