gpt4 book ai didi

python - Pycharm 警告变量未被使用

转载 作者:太空狗 更新时间:2023-10-30 02:09:52 24 4
gpt4 key购买 nike

我对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的问题吗?

最佳答案

警告是正确的。

Assigning 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只能以三种可能的方式之一退出:

  • 引发了未处理的异常(无返回值)
  • 在缩进 block 内引发异常,但标记为由上下文管理器的 __exit__ 方法处理(返回 None)。这在这个特定代码 中不会发生,因为这个数据库上下文管理器(可能来自 sqlite)不会吞噬异常。但在其他情况下值得牢记。
  • 没有错误。 cur.fetchone() 返回结果,which itself might be None如果没有数据。

关于python - Pycharm 警告变量未被使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33249605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com