python - Pycharm 警告变量未被使用

标签 python scope

我对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/

相关文章:

c++ - 条件中声明的变量范围

javascript - ajax 后 Angular 更新 $scope 变量未反射(reflect)在 UI 中

python - 加速一个计算巨大数组中邻居平均值的程序

python - 如何在字符串中指定新行以便将多行写入文件?

python - 从数据框中捕获组织名称

java - 从另一个 JSP 文件读取变量

python - 覆盖 PyGObject 中的虚拟方法

python - 如何使用子包正确打包Python3应用程序

c++ - 继承时的作用域规则 - C++

python - 为什么文档在定义 "directly"时使用单词 "scope"?