2017-05-31 97 views
0

PyCharm提醒我變量category可以在賦值之前被引用,但我不這麼認爲。PyCharm:finally塊中的變量可能在賦值之前被引用?

除應捕獲每個Exception(致命錯誤除外),最後在tryexcept塊之後調用。

try: 
     category = lst[2] 
    except: 
     category = None 
    finally: 
     if not category: #here 
      category = self.default_category 

enter image description here

你覺得呢?這是真的還是它的錯誤?

+0

也許是一個錯誤。我會看到如果在嘗試刪除警告之前將None分配給類別。 'except'下劃線是什麼? –

回答

2

也許PyCharm看到的作業,而不考慮「分配到什麼」。也就是說,None是什麼讓差異,考慮,如果你不是這樣寫道:

try: 
    category = lst[2] 
except: 
    category = Noone 
finally: 
    if not category: 
     category = self.default_category 

(或者None/1等),那麼你會得到:

NameError: name 'category' is not defined 

因爲會有例外在異常,如果lst是空的:

當發生try子句中的例外,一直沒有 除外條款通過處理(或者它有occurr編輯在except或 子句中),它將在finally子句執行後重新生成。

+0

這似乎是可能的原因。 Pycharm正在想「如果try在第一次賦值之前產生一個異常,那麼'except'在第二次賦值之前也會引發一個異常,那麼'if if not category'將會失敗。 – Kevin

相關問題