简体   繁体   中英

Pycharm warning that variable is unused

I am not very familiar with Python, especially with the scope of variables. I am trying to access a sqlite database. However, Pycharm's code inspection is warning me that the variable data is not being used.

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

Is this a pycharm problem?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM