2015-10-21 114 views
3

我对Python不是很熟悉,尤其是变量的范围。我正在尝试访问一个SQLite数据库。但是,Pycharm的代码检查警告我没有使用变量dataPycharm警告该变量未被使用

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问题吗?

+2

不,这是因为你从不使用'data = None'的值。你只需重新分配它。 –

+0

通常Pycharm会更喜欢这种风格,如果你标签启动self.data =无当你在__init创建对象__ __(self,* args) –

+0

@JeffM:这是一个局部变量,而不是一个实例属性。 – user2357112

回答

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 
+1

因此,在python中,数据变量即使在循环中初始化,在函数的任何地方都可用? – mrQWERTY

+1

我没有在这里看到一个循环..你的意思是“与”声明? yes ...如果在with语句中初始化它的外部可用 – labheshr

+1

为什么'data = data或None'?你为什么要用'None'替换'data'的某些值? – user2357112

3

警告是正确的。

指定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只能以三种可能的方式之一出口:

  • 未处理的异常上升(无返回值)
  • 将引发异常内部的缩进块,但标记为由上下文管理器的__exit__方法处理(返回None
  • 没有错误(返回cur.fetchone()的结果)
+0

对,我忘了在没有数据的情况下'fetchone'返回'None'。 –

+1

一个预期返回一个值的函数应该总是显式返回None,而不是依赖于该默认行为。否则,我不容易理解,我故意以给定的方式执行的函数并且不返回任何结果。 – Dunes