我刚加入了一家新公司,它使用mypy来强制python中的类型,我想了解如何在db类中正确地输入sqlite db连接。
以前我会这样做(为了简洁起见,我只定义init()和connect()):
import sqlite3
class DBConn:
def __init__(self, db_path):
self.db_path = db_path
self.conn = None
self.cursor = None
def connect(self):
try:
self.conn = sqlite3.connect(self.db_path)
self.cursor = self.conn.cursor()
return True
except sqlite3.Error as e:
print("Error connecting to database: {e}")
return False
现在,我已经将代码修改为如下所示(根据输入):
import sqlite3
class DBConn:
def __init__(self, db_path: str) -> None:
self.db_path = db_path
self.conn = None
self.cursor = None
def connect(self) -> bool:
try:
self.conn = sqlite3.connect(self.db_path)
self.cursor = self.conn.cursor() # warning is here
return True
except sqlite3.Error as e:
print("Error connecting to database: {e}")
return False
一旦我完成了这些更新,我就会收到来自mypy的警告,指出“None”类型的对象不能有属性“cursor”,例如,如果我将init中的初始值修改为空str,我会收到带有“str”而不是None的相同消息。
我应该如何在示例化之前正确地输入这些self变量,这样我就可以避免这个警告,或者我可以忽略它,或者有没有更好/更Python的方法来编写这个代码?
如有任何建议,不胜感激,谢谢!
1条答案
按热度按时间m4pnthwp1#
对于将来寻找答案的任何人,您可以使用MyPy类型Optional,如下所示: