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 ?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With