我对Python不太熟悉,尤其是变量的范围。我正在尝试访问sqlite数据库。但是,Pycharm的代码检查警告我该变量data未被使用。
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
Run Code Online (Sandbox Code Playgroud)
这是一个pycharm问题吗?
警告是正确的。
分配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()
Run Code Online (Sandbox Code Playgroud)
上面的代码是等效的,因为该函数getIndexFromDB只能以以下三种可能的方式之一退出:
__exit__上下文管理器的方法处理(None返回)cur.fetchone()返回结果)使用下面的代码而不是在最顶部分配数据怎么样?那是安全的,并且也可以消除警告......
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
Run Code Online (Sandbox Code Playgroud)