From: Séamus Ó Ceanainn Date: Wed, 10 Dec 2025 17:14:25 +0000 (-0500) Subject: Fix return type hint for `Query.get()` X-Git-Tag: rel_2_0_46~19^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=7b2196e15f370796b877b7e8350a7883335fbae3;p=thirdparty%2Fsqlalchemy%2Fsqlalchemy.git Fix return type hint for `Query.get()` `Query[_T].get(...)` should return `Optional[_T]` instead of `Optional[Any]`. This is typed correctly when migrating to `Session.get(_T, ...)`. By typing the legacy `Query.get(...)` call first, it should make migrations easier on developers, as it splits up the type checking improvements (and subsequent errors which may be discovered) from the `Query.get()` to `Session.get()` migration. This pull request is: - [x] A documentation / typographical / small typing error fix - Good to go, no issue or tests are needed - [ ] A short code fix - please include the issue number, and create an issue if none exists, which must include a complete example of the issue. one line code fixes without an issue and demonstration will not be accepted. - Please include: `Fixes: #` in the commit message - please include tests. one line code fixes without tests will not be accepted. - [ ] A new feature implementation - please include the issue number, and create an issue if none exists, which must include a complete example of how the feature would look. - Please include: `Fixes: #` in the commit message - please include tests. **Have a nice day!** Closes: #13028 Pull-request: https://github.com/sqlalchemy/sqlalchemy/pull/13028 Pull-request-sha: 38ec0c3ae072f8c7b62134dd017579a6a249219f Change-Id: I7ae8e59bc0bd0a25c65de3804d60f6c2b6f50151 (cherry picked from commit 9cd9b6b5896333f779f484c73f3c1119448305b5) --- diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py index 620cd2116c..a563025093 100644 --- a/lib/sqlalchemy/orm/query.py +++ b/lib/sqlalchemy/orm/query.py @@ -1042,7 +1042,7 @@ class Query( ":meth:`_orm.Query.get`", alternative="The method is now available as :meth:`_orm.Session.get`", ) - def get(self, ident: _PKIdentityArgument) -> Optional[Any]: + def get(self, ident: _PKIdentityArgument) -> Optional[_T]: """Return an instance based on the given primary key identifier, or ``None`` if not found. diff --git a/test/typing/plain_files/orm/typed_queries.py b/test/typing/plain_files/orm/typed_queries.py index 1e305b7b20..ae83f402d3 100644 --- a/test/typing/plain_files/orm/typed_queries.py +++ b/test/typing/plain_files/orm/typed_queries.py @@ -1,5 +1,7 @@ from __future__ import annotations +from typing import assert_type +from typing import Optional from typing import Tuple from sqlalchemy import Column @@ -133,6 +135,8 @@ def t_legacy_query_single_entity() -> None: # EXPECTED_TYPE: User reveal_type(q1.one()) + assert_type(q1.get(5), Optional[User]) + # EXPECTED_TYPE: List[User] reveal_type(q1.all())