]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
Document generic type parameters to FunctionElement and GenericFunction (#9079)
authorStephen Rosen <sirosen@globus.org>
Tue, 14 Mar 2023 19:18:14 +0000 (14:18 -0500)
committerGitHub <noreply@github.com>
Tue, 14 Mar 2023 19:18:14 +0000 (20:18 +0100)
* Document type parameters to FunctionElement

Add a note to FunctionElement which indicates that the type is a
typing.Generic class and points at GenericFunction examples for a
specific example usage.

A minimal reference is made to type checkers and IDEs as use-cases in
order to try to contextualize this as an optional feature which
supports particular use cases.

Append to the GenericFunction examples a case which uses `DateTime`
but also includes the generic type parameter (`datetime.datetime`).

* Fix type annotated function usage example

lib/sqlalchemy/sql/functions.py

index 5f2e67288cac6996f950883dcc650cb75472d7fd..0952ca0f1b0825867fb04fe03fdffbf9462dd540 100644 (file)
@@ -100,6 +100,11 @@ def register_function(identifier, fn, package="_default"):
 class FunctionElement(Executable, ColumnElement[_T], FromClause, Generative):
     """Base for SQL function-oriented constructs.
 
+    This is a `generic type <https://peps.python.org/pep-0484/#generics>`_,
+    meaning that type checkers and IDEs can be instructed on the types to
+    expect in a :class:`_engine.Result` for this function. See
+    :class:`.GenericFunction` for an example of how this is done.
+
     .. seealso::
 
         :ref:`tutorial_functions` - in the :ref:`unified_tutorial`
@@ -1249,6 +1254,19 @@ class GenericFunction(Function[_T]):
         >>> print(func.geo.buffer())
         {printsql}"ST_Buffer"()
 
+    Type parameters for this class as a
+    `generic type <https://peps.python.org/pep-0484/#generics>`_ can be passed
+    and should match the type seen in a :class:`_engine.Result`. For example::
+
+        class as_utc(GenericFunction[datetime.datetime]):
+            type = DateTime()
+            inherit_cache = True
+
+    The above indicates that the following expression returns a ``datetime``
+    object::
+
+        connection.scalar(select(func.as_utc()))
+
     .. versionadded:: 1.3.13  The :class:`.quoted_name` construct is now
        recognized for quoting when used with the "name" attribute of the
        object, so that quoting can be forced on or off for the function