2014-10-02 55 views
0

如果我想確保某些變量是函數輸入參數中的某些類型的數據,我該如何檢查它「Python的」?什麼是Pythonic方法來確保某個類型或參數正確傳遞到函數/類中?

例如,這是你應該這樣做的方式嗎?

def test1(int1): 
    if type(int1) == int: 
     int1 = int1 + 4 
    else: 
     raise(RuntimeError) 
    return int1 

我確定有人問過這個問題,但我真的不知道要搜索什麼。

附錄問題:函數註釋如何發揮所有這一切?

+0

https://docs.python.org/2/library/functions.html#isinstance – Jasper 2014-10-02 16:12:08

回答

1

那麼,Python的人喜歡說請求寬恕比請求許可更容易(EAFP)。也許是這樣的:

def test1(int1): 
    try: 
    int1 = int1 + 4 
    except TypeError: 
    raise RuntimeError 
    return int1 

只要嘗試一下,並捕捉錯誤,如果失敗。

+1

但是,如果你正在做的是重新認識錯誤,然後穿上」不要嘗試 - 除了一切; Python已經爲你提出了一個錯誤。如果你想在發生異常時做一些非功能性的事情,比如日誌記錄,那麼在一個裝飾器中執行 - 讓函數的實現儘可能乾淨。 – PaulMcG 2014-10-02 16:31:04

3

我不會檢查參數的類型。 Python會引發錯誤,只有當它不能處理你傳遞的對象和int對象4之間的加成:

>>> def test1(int1): 
...  return int1 + 4 
... 
>>> test1(1) 
5 
>>> test1(1.5) 
5.5 
>>> test1('a') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 2, in test1 
TypeError: cannot concatenate 'str' and 'int' objects 

如果你想提高不同的錯誤,趕上TypeError

def test1(int1): 
    try: 
     return int1 + 4 
    except TypeError: 
     raise RuntimeError 
+0

大多數人讓用戶知道如何記錄該功能的「標準」方式到底是什麼?您是否親自說過,在函數的文檔字符串中寫入參數類型?你使用註釋嗎?你如何向你的用戶(以及你未來的自我)傳達什麼樣的論據應該是正確的? – johnzilla 2014-10-02 16:18:35

+0

@johnzilla,如果你使用Python 3.x,你可以使用[Function Annotation](http://legacy.python.org/dev/peps/pep-3107/)。否則,docstring。 – falsetru 2014-10-02 16:27:29

1

如果你真的想請檢查arg類型是否使用pythonic方式isinstance

def test1(int1): 
    if is instance(int1, int): 
     int1 = int1 + 4 
    else: 
     raise(RuntimeError) 

但是,作爲@falsetru,也不想檢查類型。 Python已經做得很好。

此外,我會使用tryexception來改變流程,而不是增加錯誤。

0

不確定這是否正確。但是你嘗試這樣的: -

def test1(int1): 
    try: 
     int1 = int1 + 4 
    except: 
     raise(RuntimeError) 

    return int1 
相關問題