pythoninterfacepython-typing

Python type hinting with db-api


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 ?


Solution

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