我想添加 db-api 类型提示,例如:
def test_connect() -> Connection :
...
知道我正在动态加载模块驱动程序(意思是,没有像“pyodbc.Connection”这样的硬编码),并且Python中没有正式的接口契约。
有什么想法吗?
虽然晚了大约 5 年,但我今天也在寻找同样的东西。
这是我使用打字模块中的 Protocol
实现的
DBAPI 2.0类
from collections.abc import Sequence, Mapping
from typing import Any, Protocol
class Connection(Protocol):
def close(self) -> None:
...
def commit(self) -> None:
...
def cursor(self, *args, **kwargs) -> Cursor:
...
class Cursor(Protocol):
description: Sequence[Any] | None
rowcount: int
arraysize: int
def close(self) -> None:
...
def execute(self, operation: Any, *args, **kwargs) -> None:
...
def executemany(
self,
operation: Any,
seq_of_parameters: Sequence[Any] | Mapping[Any, Any],
*args,
**kwargs
) -> None:
...
def fetchone(self) -> Sequence[Any] | None:
...
def fetchmany(self, size: int = 0) -> Sequence[Sequence[Any]]:
...
def fetchall(self, size: int = 0) -> Sequence[Sequence[Any]]:
...
def setinputsizes(self, sizes: Sequence[Any]) -> None:
...
def setoutputsize(self, size: Any, column: int | None = None) -> None:
...
自从编写了之前的答案以来,现在有 typeshed 中的 DB API 存根。有问题的存根具有有限的稳定性保证,但如果您可以忍受,您可以将它们用于:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from _typeshed.dbapi import DBAPIConnection, DBAPICursor