2010-11-29 21 views
4

定義功能,什麼是創建一個集合時處理空*參數的pythonic方法?

MyFunction的(說法,*參數): [做些什麼來論證[參數]在* 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: 

這可能會工作,但似乎並沒有「Python化」就夠了嗎?

這是(是否存在)一種標準方法來處理* 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) 
+0

你寫'導出()`或`SubsetOutput()`? – 2010-11-29 05:10:11

+0

好吧,都是。導出是協程管道開始的'源'。如果使用* args調用導出函數,則在發送管道之前,需要將* args從「源」中取出。 – 2010-11-29 05:20:12

回答

3

有沒有辦法通過一個「整組」參數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]) 
0

只需選中它不是沒有,你不必創建一個單獨的參數

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

如何:

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