Pycharm warning that variable is unused

The warning is correct.

Assigning data = None is a useless line and may as well be deleted.

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()

The code above is equivalent, because the function getIndexFromDB can only exit in one of three possible ways:

  • An unhandled exception is raised (no return value)
  • An exception is raised inside the indented block, but marked as handled by the __exit__ method of the context manager (None is returned). That can not happen in this particular code because this db context manager, presumably from sqlite, is not swallowing exceptions. But it's worth to keep in mind in other cases.
  • No errors. The result of cur.fetchone() is returned, which itself might be None in case of no data.

How about use the below code instead of assigning data at the very top? Thats safe and cures the warning as well...

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

Tags:

Python

Scope