2015-10-21 111 views
3

我對Python不是很熟悉,尤其是變量的範圍。我正在嘗試訪問一個SQLite數據庫。但是,Pycharm的代碼檢查警告我沒有使用變量dataPycharm警告該變量未被使用

def getIndexFromDB(self, user, username, domID): 
    data = None #warning that this variable is unused 
    with lite.connect(self.DBName) as con: 
     cur = con.cursor() 
     cur.execute('PRAGMA foreign_keys = ON') 
     cur.execute('select idx from Upass where username = ? and uname = ? and dom = ?', (user, username, domID)) 
     data = cur.fetchone() 
    return data 

這是一個pycharm問題嗎?

+2

不,這是因爲你從不使用'data = None'的值。你只需重新分配它。 –

+0

通常Pycharm會更喜歡這種風格,如果你標籤啓動self.data =無當你在__init創建對象__ __(self,* args) –

+0

@JeffM:這是一個局部變量,而不是一個實例屬性。 – user2357112

回答

2

如何使用下面的代碼而不是在頂部分配數據?這是安全的,並治癒警告以及...

def getIndexFromDB(self, user, username, domID): 
    with lite.connect(self.DBName) as con: 
     cur = con.cursor() 
     cur.execute('PRAGMA foreign_keys = ON') 
     cur.execute('select idx from Upass where username = ? and uname = ? and dom = ?', (user, username, domID)) 
     data = cur.fetchone() 
    data = data or None 
    return data 
+1

因此,在python中,數據變量即使在循環中初始化,在函數的任何地方都可用? – mrQWERTY

+1

我沒有在這裏看到一個循環..你的意思是「與」聲明? yes ...如果在with語句中初始化它的外部可用 – labheshr

+1

爲什麼'data = data或None'?你爲什麼要用'None'替換'data'的某些值? – user2357112

3

警告是正確的。

指定data = None是無用的行,也可能被刪除。

def getIndexFromDB(self, user, username, domID): 
    with lite.connect(self.DBName) as con: 
     cur = con.cursor() 
     cur.execute('PRAGMA foreign_keys = ON') 
     cur.execute('select idx from Upass where username = ? and uname = ? and dom = ?', (user, username, domID)) 
     return cur.fetchone() 

上面的代碼是等價的,因爲該函數getIndexFromDB只能以三種可能的方式之一出口:

  • 未處理的異常上升(無返回值)
  • 將引發異常內部的縮進塊,但標記爲由上下文管理器的__exit__方法處理(返回None
  • 沒有錯誤(返回cur.fetchone()的結果)
+0

對,我忘了在沒有數據的情況下'fetchone'返回'None'。 –

+1

一個預期返回一個值的函數應該總是顯式返回None,而不是依賴於該默認行爲。否則,我不容易理解,我故意以給定的方式執行的函數並且不返回任何結果。 – Dunes