Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 997
Stef Avatar asked Sep 27 '18 09:09

Stef


People also ask

Is type hinting good practice Python?

Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.

How do you type hinting in Python?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.

What is DB API in Python?

The standard for accessing a database in Python is the Python DB-API. This specifies a set of standard interfaces for modules that wish to allow Python to access a specific database. The standard is described in PEP 249 (https://www.python.org/dev/peps/pep-0249)—a PEP is a Python Enhancement Proposal.


1 Answers

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.

like image 92
Michael0x2a Avatar answered Oct 12 '22 17:10

Michael0x2a