2017-06-27 52 views
0

我有一個腳本要求用戶輸入大量日期,大部分功能與下面的類似。這需要考慮到無效的日期格式:在python中凝聚重複try-except語句

import numpy as np 
import pandas as pd 
import xlwings as xw 
import datetime as dtt 

def week_init(): 
     """Creates an initial week datetime and determines what the checking cutoff 
     'beforeday' to be used in Stage 2 is.""" 
     week = input('Week to check: MM/DD/YYYY\n') 
     switch = 1 
     while switch == 1: 
      try: 
       week = dtt.datetime.strptime(week,'%m/%d/%Y') #turns input to a datetime 
       switch = 0 
      except ValueError: 
       week = input('Unrecognized date format, please try again: MM/DD/YYYY\n') 
     beforeday = (input('Check days before date (Press enter to use today): MM/DD/YYYY\n') 
      or dtt.date.today()) 
     if (beforeday != dtt.date.today()): 
      switch = 1 
      while switch == 1: 
       try: 
        beforeday = dtt.datetime.strptime(beforeday,'%m/%d/%Y') 
        switch = 0 
       except ValueError: 
        beforeday = input('Unrecognized date format, please try again: MM/DD/YYYY\n') 
     return week, beforeday 

也有檢查的指標給定日期的功能,必須處理一個給定的日期不匹配任何索引:

def spotmap(week, bam, pt): 
    """Maps the pivoted data for the chosen week to the BAM dataframe's SD column.""" 
    print('Mapping data to BAM... ',end=''), 
    switch = 1 
    while switch == 1: 
     try: 
      bam['SD'] = bam.index.to_series().map(pt.fillna(0)['len',week]) 
      switch = 0 
     except KeyError: 
      print('Invalid date, please try again.') 
      week = input('Week start date (Sunday): MM/DD/YYYY\n') 
    print('Done') 
    return bam 

由於腳本在獲取這些日期後有許多事情要做,我不希望它在遇到問題時崩潰,但是如果沒有正確的日期輸入,它就無法繼續,因此我現在將它與這些「切換「變量來控制它何時願意繼續有效的日期。正如你所看到的,儘管如此,這些try/except塊正在迅速膨脹其他直截了當的代碼。有沒有辦法來壓縮這些東西?另外,比開關更好的方法?

Repetitive Try and Except Clauses

這些問題的答案在這裏建議的裝飾,但據我可以從文檔和網頁一樣this告訴,這些都是用於包裝的功能,而不是更換內部代碼塊。另外,我不確定它們會是多麼有用,因爲try/except塊在他們試圖完成的任務中(例如,他們正在改變哪個變量)大多是獨一無二的。我想我真的只是希望得到更好的語法。

+2

[codereview.se]可能是一個更好的地方問這個,我想。 –

+0

啊,好的。那麼我會那樣做。 –

回答

0

嘗試在功能中重複調用以減少膨脹。這是一個刺:

import numpy as np 
import pandas as pd 
import xlwings as xw 
import datetime as dtt 

def loop_until_good(func, arg): 
    looping = True 
    while looping: 
     (arg, looping) = func(arg) 
     return arg 

def make_datetime(date): 
    try: 
     date = dtt.datetime.strptime(date,'%m/%d/%Y') #turns input to a datetime 
     return date, False 
    except ValueError: 
     date = input('Unrecognized date format, please try again: MM/DD/YYYY\n') 
     return date, True 

def bammit(arg): 
    (bam, week, pt) = arg 
    try: 
     bam['SD'] = bam.index.to_series().map(pt.fillna(0)['len',week]) 
     return (bam, week, pt), False 
    except KeyError: 
     print('Invalid date, please try again.') 
     week = input('Week start date (Sunday): MM/DD/YYYY\n') 
     return (bam, week, pt), True 

def week_init(): 
     """Creates an initial week datetime and determines what the checking cutoff 
     'beforeday' to be used in Stage 2 is.""" 
     week = str(input('Week to check: MM/DD/YYYY\n')) 
     print type(week) 
     print week 
     loop_until_good(make_datetime, week) 
     beforeday = (input('Check days before date (Press enter to use today): MM/DD/YYYY\n') 
      or dtt.date.today()) 
     if (beforeday != dtt.date.today()): 
      loop_until_good(make_datetime, beforeday) 
     return week, beforeday 

def spotmap(week, bam, pt): 
    """Maps the pivoted data for the chosen week to the BAM dataframe's SD column.""" 
    print('Mapping data to BAM... ') 
    loop_until_good(bammit, (bam, week, pt)) 
    print('Done') 
    return bam