使用 db-api 进行 Python 类型提示

问题描述 投票:0回答:3

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

def test_connect() -> Connection :
...

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

有什么想法吗?

python interface type-hinting
3个回答
4
投票

您可能想在这里使用协议

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

最后一点:我知道 mypy 支持协议,但我不确定其他类型检查器是否支持。有一个开放 PEP 可以正式将协议引入 Python 类型生态系统——一旦 PEP 被接受,其他类型检查器可能会添加对协议的支持(如果还没有的话)。


3
投票

虽然晚了大约 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:
        ...


2
投票

自从编写了之前的答案以来,现在有 typeshed 中的 DB API 存根。有问题的存根具有有限的稳定性保证,但如果您可以忍受,您可以将它们用于:

from typing import TYPE_CHECKING if TYPE_CHECKING: from _typeshed.dbapi import DBAPIConnection, DBAPICursor
    
© www.soinside.com 2019 - 2024. All rights reserved.