2017-08-04 95 views
0

我有一個接受整數年的函數,但我也希望用戶能夠傳遞字符串'ALL',並且仍然能夠返回。如何簡化相互依賴但導致相同結果的兩個條件?

我有這個醜陋的代碼現在:

if type(year) != str or (type(year) == str and year.upper() != 'ALL'): 
    total_results = self.filterResultsByYear(total_results, year, year2) 

結果默認情況下,過濾,本年度,並且可以通過其他年份進行過濾,但如果用戶想不過濾,他們有今年通過'全部'。

我寫上述憎惡的原因是,如果我只有if year.upper() != 'ALL'如果我傳遞一個整數,則得到一個TypeError。如果我把if type(year) != str and year.upper() != 'ALL'我仍然得到相同的錯誤。上面的代碼看起來非常難看,我想讓它變得更加pythonic。我必須做什麼工具?

+1

「year」是一個字符串但不是「all」時的預期行爲是什麼? – DyZ

+0

你總是期望有效的輸入?如果不是,我會說只是檢查是否是有效年份或根本不應用過濾器。 – KGS

+0

@DYZ我想拋出錯誤/提醒用戶輸入無效。基本上我想過濾器默認應用,如果用戶提供一個int,但如果用戶提供了一個字符串,並且該字符串恰好是「all」,那麼我想忽略該過濾器。 – PolarBearITS

回答

1

根據什麼total_resultsyear2是,你想如何處理它們:

try: 
    year = int(year) 
    total_results = self.filterResultsByYear(total_results, year, year2) 
except ValueError: 
    if not isinstance(year, (str, unicode)): 
     raise # Not string, unicode or coercible to an integer. 
    if year.lower() == 'all': 
     # Your logic here. 
    else: 
     # String but not 'all'. Exception handling. 

再見的方式,檢查類等效一個使用isinstance(object, class)isinstance(object, (class 1, class 2, ...))

+0

我希望代碼流的工作方式是過濾器應用,除非年份等於「全部」,那麼它將被忽略。默認情況下應用過濾器。 – PolarBearITS