From 1504aa9f9f95964ee73030a76941b8169e04d5bc Mon Sep 17 00:00:00 2001 From: Mike Bayer Date: Wed, 8 Mar 2023 12:35:27 -0500 Subject: [PATCH] Use independent TypeVar for ColumnElement.cast Fixed typing issue where :meth:`.ColumnElement.cast` did not allow a :class:`.TypeEngine` argument independent of the type of the :class:`.ColumnElement` itself, which is the purpose of :meth:`.ColumnElement.cast`. Fixes: #9451 Change-Id: I68119c6a9e8bf896715eea79be2b4f36b1c141de --- doc/build/changelog/unreleased_20/9451.rst | 8 ++++++++ lib/sqlalchemy/sql/elements.py | 2 +- test/ext/mypy/plain_files/sql_operations.py | 10 ++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 doc/build/changelog/unreleased_20/9451.rst diff --git a/doc/build/changelog/unreleased_20/9451.rst b/doc/build/changelog/unreleased_20/9451.rst new file mode 100644 index 0000000000..5ed6b7e944 --- /dev/null +++ b/doc/build/changelog/unreleased_20/9451.rst @@ -0,0 +1,8 @@ +.. change:: + :tags: bug, typing + :tickets: 9451 + + Fixed typing issue where :meth:`.ColumnElement.cast` did not allow a + :class:`.TypeEngine` argument independent of the type of the + :class:`.ColumnElement` itself, which is the purpose of + :meth:`.ColumnElement.cast`. diff --git a/lib/sqlalchemy/sql/elements.py b/lib/sqlalchemy/sql/elements.py index a416b6ac09..ef4587e187 100644 --- a/lib/sqlalchemy/sql/elements.py +++ b/lib/sqlalchemy/sql/elements.py @@ -1635,7 +1635,7 @@ class ColumnElement( co._is_clone_of = selectable._is_clone_of.columns.get(key) return key, co - def cast(self, type_: _TypeEngineArgument[_T]) -> Cast[_T]: + def cast(self, type_: _TypeEngineArgument[_OPT]) -> Cast[_OPT]: """Produce a type cast, i.e. ``CAST( AS )``. This is a shortcut to the :func:`_expression.cast` function. diff --git a/test/ext/mypy/plain_files/sql_operations.py b/test/ext/mypy/plain_files/sql_operations.py index c55442be99..d658f3d50f 100644 --- a/test/ext/mypy/plain_files/sql_operations.py +++ b/test/ext/mypy/plain_files/sql_operations.py @@ -2,8 +2,11 @@ import typing from sqlalchemy import and_ from sqlalchemy import Boolean +from sqlalchemy import cast from sqlalchemy import column +from sqlalchemy import DateTime from sqlalchemy import false +from sqlalchemy import Float from sqlalchemy import func from sqlalchemy import Integer from sqlalchemy import or_ @@ -75,6 +78,13 @@ and_(c1.notlike("x")) and_(c1.not_ilike("x")) and_(c1.notilike("x")) +# issue #9451 +s1 = c1.cast(Integer) +s2 = c1.cast(Float) +s3 = c1.op("foobar")("operand").cast(DateTime) +s4 = cast(c1, Float) +s5 = cast(c1.op("foobar")("operand"), DateTime) + if typing.TYPE_CHECKING: -- 2.47.2