Pycharm警告变量未使用

mrQ*_*RTY 5 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
Run Code Online (Sandbox Code Playgroud)

这是一个pycharm问题吗?

wim*_*wim 6

警告是正确的。

分配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()返回结果)


lab*_*shr 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
Run Code Online (Sandbox Code Playgroud)

  • 就我个人而言,我更喜欢“返回数据或无”,但它们在功能上是等效的。 (2认同)