Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pycharm warning that variable is unused

Tags:

python

scope

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?

like image 961
mrQWERTY Avatar asked Oct 21 '15 01:10

mrQWERTY


2 Answers

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.
like image 99
wim Avatar answered Sep 27 '22 21:09

wim


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
like image 38
labheshr Avatar answered Sep 27 '22 19:09

labheshr