我刚加入一家使用 mypy 强制执行 python 类型的新公司,我想了解如何在数据库类中正确键入 sqlite 数据库连接。
以前我会做这样的事情(为了简洁起见,我只定义了 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 的警告,即“无”类型的对象不能在我分配 self.cursor 的地方具有属性“cursor”。例如,如果我将 init 中的初始值修改为空 str,我会得到与“str”相同的消息,而不是 None。
我应该如何在实例化之前正确输入这些 self vars 才能避免这个警告?或者我只是忽略它?或者是否有更好/更 pythonic 的方式来编写代码?
非常感谢任何建议,非常感谢!
对于任何人在未来寻找答案,您可以使用 MyPy 类型 Optional 如下:
import sqlite3
from typing import Optional
class DB:
def __init__(self, db_path: str) -> None:
self.db_path = db_path
self.conn: Optional[sqlite3.Connection] = None
self.cursor: Optional[sqlite3.Cursor] = None
def connect(self) -> bool:
try:
self.conn = sqlite3.connect(self.db_path)
self.conn.row_factory = sqlite3.Row
self.cursor = self.conn.cursor()
print("Connection successful")
return True
except sqlite3.Error as e:
print(f"Error connecting to database: {e}")
return False