From: Denis Laxalde Date: Tue, 27 Apr 2021 12:07:36 +0000 (+0200) Subject: Illustrate type annotations in row factories documentation X-Git-Tag: 3.0.dev0~63^2~10 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=7aa7b470221a777223de3ce087a5234c4f75d697;p=thirdparty%2Fpsycopg.git Illustrate type annotations in row factories documentation --- diff --git a/docs/advanced/rows.rst b/docs/advanced/rows.rst index c404c2fb8..ed53f335d 100644 --- a/docs/advanced/rows.rst +++ b/docs/advanced/rows.rst @@ -16,21 +16,26 @@ This can be implemented as a class, for instance: .. code:: python + from typing import Any, Sequence + from psycopg3 import BaseCursor + class DictRowFactory: - def __init__(self, cursor): + def __init__(self, cursor: BaseCursor[Any, dict[str, Any]]): self.fields = [c.name for c in cursor.description] - def __call__(self, values): + def __call__(self, values: Sequence[Any]) -> dict[str, Any]: return dict(zip(self.fields, values)) or as a plain function: .. code:: python - def dict_row_factory(cursor): + def dict_row_factory( + cursor: BaseCursor[Any, dict[str, Any]] + ) -> Callable[[Sequence[Any]], dict[str, Any]]: fields = [c.name for c in cursor.description] - def make_row(values): + def make_row(values: Sequence[Any]) -> dict[str, Any]: return dict(zip(fields, values)) return make_row @@ -50,6 +55,11 @@ Later usages of `row_factory` override earlier definitions; for instance, the `row_factory` specified at `Connection.connect()` can be overridden by passing another value at `Connection.cursor()`. +.. note:: By declaring type annotations on the row factory used in + `Connection` or `Cursor`, rows retrieved by `.fetch*()` calls will have the + correct return type (i.e. a `dict[str, Any]` in previous example) and your + code can be type checked with a static analyzer such as mypy. + Available row factories -----------------------