Add types to _get_db#12462
Conversation
There was a problem hiding this comment.
Pull request overview
Adds a type cast to _get_db() in openlibrary/core/db.py to make the cached DB accessor appear as a PostgresDB to type checkers (and imports the associated typing helpers).
Changes:
- Import
castandPostgresDB. - Cast the return value of
web.database(**web.config.db_parameters)toPostgresDB.
| @functools.cache | ||
| def _get_db(): | ||
| return web.database(**web.config.db_parameters) | ||
| return cast(PostgresDB, web.database(**web.config.db_parameters)) |
There was a problem hiding this comment.
_get_db() can return a SQLite-backed web.py DB in unit tests (e.g., tests set web.config.db_parameters = {"dbn": "sqlite", ...}), so casting the result of web.database(...) to PostgresDB is too narrow/misleading and can hide type errors (type checker will allow Postgres-only attributes even though runtime may be SQLite). Use a broader return type (common base/interface/Protocol or Union of supported DB types) and add an explicit return type annotation instead of forcing PostgresDB here.
Note: This might cause more trouble than it's worth, since the webpy DB implementation isn't well-typed. But all the tests are passing...
Technical
Testing
Screenshot
Stakeholders