我对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
这是一个pycharm问题吗?
答案 0 :(得分:4)
警告是正确的。
分配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()
的结果)答案 1 :(得分:3)
如何使用以下代码而不是在最顶端分配数据?多数民众赞成安全,并治愈警告......
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