Python和db-api的类型提示

10

我想添加db-api类型提示,例如:

def test_connect() -> Connection :
...

了解我正在动态加载模块驱动程序(意思是没有像“pyodbc.Connection”这样的硬编码方式),而且在 Python 中没有正式的接口契约。

有什么想法吗?


你的目的是什么?动态加载模块?这可能与类型提示无关。 - Xiao Tan
3个回答

4

在这里,您可能想要使用协议

简而言之,在您的代码库中定义一个自定义协议,其中包含任何“连接”对象必须具有的方法签名。然后,只要它包含所指定方法的方法,您就可以自由返回任何任意对象。

最后说明一下:我知道mypy支持协议,但我不确定其他类型检查器是否支持。有一个开放的 PEP,旨在正式介绍协议到Python类型注释生态系统 - 在该PEP被接受后,其他类型检查器可能会添加对协议的支持,如果他们还没有这样做的话。


2
PEP 544已被接受,并且现在是Python 3.8+的标准。 - Julian Mehnle

2
只晚了大约5年,但我今天也在寻找同样的东西。 这是我使用typing模块中的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 | None
    rowcount: int
    arraysize: int

    def close(self) -> None:
        ...

    def execute(self, operation: Any, *args, **kwargs):
        ...

    def executemany(
        self, operation: Any, seq_of_parameters: Sequence | Mapping, *args, **kwargs):
        ...

    def fetchone(self) -> Sequence | None:
        ...

    def fetchmany(self, size: int = 0) -> Sequence[Sequence]:
        ...

    def fetchall(self, size: int = 0) -> Sequence[Sequence]:
        ...

    def setinputsizes(self, sizes: Sequence):
        ...

    def setoutputsize(self, size: Any, column: int | None = None):
        ...


0
自从之前的回答写出来以后,现在有了 typeshed中的DB API stubs。所谓的stubs带有有限的稳定性保证,但如果你可以容忍,你可以使用它们来:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from _typeshed.dbapi import DBAPIConnection, DBAPICursor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接