-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Description
fbcce8e introduced type hints for the row_factory attributes of sqlite3.Connection and sqlite3.Cursor:
_RowFactoryOptions: TypeAlias = type[Row] | Callable[[Cursor, Row], object] | None
# ...
class Connection:
# ...
row_factory: _RowFactoryOptions
# ...
class Cursor:
# ...
row_factory: _RowFactoryOptions
It's wrong
However, the second argument to the Callable is not correct: It should be a tuple instead of a Row. The Python documentation has this to say:
row_factory ... Can be set to the included sqlite3.Row; or a callable that accepts two arguments, a Cursor object and the tuple of row values
In Python 3.13.1 (at least), the 2nd argument to the row_factory is indeed a tuple, see below.
Reproduce with false positive from type checker
Test file:
$ cat > /tmp/test.py
import sqlite3
from typing import Any
def my_factory(cursor: sqlite3.Cursor, row: tuple[Any, ...]) -> tuple[Any, ...]:
print(type(cursor), type(row))
return row
conn: sqlite3.Connection = sqlite3.connect(":memory:")
conn.row_factory = my_factory
print(conn.execute("SELECT 1").fetchall())
Running it shows a tuple 2nd argument:
$ python --version
Python 3.13.1
$ python /tmp/test.py
<class 'sqlite3.Cursor'> <class 'tuple'>
[(1,)]
The type checker produces an error for the correct code:
$ pyright --version
pyright 1.1.408
$ pyright /tmp/test.py
/tmp/test.py
/tmp/test.py:9:20 - error: Cannot assign to attribute "row_factory" for class "Connection"
Type "(cursor: Cursor, row: tuple[Any, ...]) -> tuple[Any, ...]" is not assignable to type "_RowFactoryOptions"
Type "(cursor: Cursor, row: tuple[Any, ...]) -> tuple[Any, ...]" is not assignable to type "type[Row]"
Type "(cursor: Cursor, row: tuple[Any, ...]) -> tuple[Any, ...]" is not assignable to type "(Cursor, Row) -> object"
Parameter 2: type "Row" is incompatible with type "tuple[Any, ...]"
"Row" is not assignable to "tuple[Any, ...]"
"FunctionType" is not assignable to "None" (reportAttributeAccessIssue)
1 error, 0 warnings, 0 informations
Expected behavior
Therefore, presumably it should be a Callable[[Cursor, tuple[Any, ...], object], or something similar.
_RowFactoryOptions: TypeAlias = type[Row] | Callable[[Cursor, tuple[Any, ...]], object] | None
I am not sure if that is indeed the best way to type hint this, or how PRs are expected to work here; I also also don't have time for more than a bug report right now, so I'm only opening an issue instead of a PR.