13

I would like to add db-api type hinting, e.g:

def test_connect() -> Connection :
...

Knowing that I'm loading module driver dynamically (Meaning, no hard-coded like "pyodbc.Connection"), and that there is no formal interface contract in Python.

Any idea ?

1
  • what's your purpose? dynamic loading module? that maybe have nothing to do with type hint Commented Sep 27, 2018 at 10:02

3 Answers 3

6

Only about 5 years late, but I was looking for the same thing today. Here is my implementation of the DBAPI 2.0 classes using Protocol from the typing module

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:
        ...

Sign up to request clarification or add additional context in comments.

Comments

5

Since the previous answers were written, there are now DB API stubs in typeshed. The stubs in question come with limited stability guarantees, but if you can tolerate that, you can use them with:

from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from _typeshed.dbapi import DBAPIConnection, DBAPICursor

Comments

4

You'll probably want to use protocols here.

In short, you define a custom protocol in your codebase containing signatures for methods any "connection" object must have. Then, you're free to return any arbitrary object so long as it contains those methods with the specified methods.

Final note: I know that mypy supports protocols, but I'm not sure if other type checkers do. There's an open PEP to formally introduce protocols to the Python typing ecosystem -- presumably other type checkers will add support for protocols once that PEP is accepted, if they haven't already.

1 Comment

PEP 544 has been accepted and is now standard for Python 3.8+.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.