2012-03-27 50 views
0

通常情況下,類型檢查是在Python和良好reason--你應該知道類型的數據正在傳遞什麼給你的函數,如果你的代碼是精心設計的皺起了眉頭。檢查作爲通配符Python類型

但是,我正在處理一種舊的編程語言,其中的一部分有一些與輸入驗證和兼容性有關的獨特挑戰。

這是用來做一些基本的類型檢查的功能,實際運行之前的函數:

def argcheck(stack, funcname, arglist, exceptlist): 
     """This function checks if arguments are valid and then passes back a list of them in order if they are. 
     stack should contain the stack. 
     funcname should contain the display name of the function for the exception. 
     arglist should contain a list of lists of valid types to be checked against. 
     exceptlist contains the information the exception should contain if the item does not match.""" 
     returnlist=[] 
     count=0 
     for xtype in arglist: 
      if stack[-1] in xtype: 
       returnlist.append(stack[-1]) 
       stack.pop() 
      else: 
       raise Exception(funcname, exceptlist[count]) 

偶爾,我需要一些東西來匹配任何類型。我如何製作所有類型的列表,或者在列表中返回true,如果有任何事情嘗試匹配它?

+1

「通常情況下,類型檢查時在Python皺起了眉頭,好reason--你應該如果你的代碼設計得很好,就知道傳遞給你函數的數據是什麼樣的。「 < - 這根本不是原因。原因是「一切都是對象」,所以一般來說功能不應該在意。 – SpliFF 2012-03-27 06:58:24

+0

對象有不同的方法。如果我的函數需要一個字符串類型的參數,而且我希望添加數字,那麼這對我來說就不太好。我會問的問題是爲什麼我的函數是首先添加字符串的數字? – Kelketek 2012-03-27 07:10:32

回答

1

使用一個空的列表,以匹配任何類型,並更改匹配條件是True如果xtype爲空:

def argcheck(stack, funcname, arglist, exceptlist): 
    returnlist=[] 
    count=0 
    for xtype in arglist: 
     if not xtype or stack[-1] in xtype: 
      returnlist.append(stack[-1]) 
      stack.pop() 
     else: 
      raise Exception(funcname, exceptlist[count])