From: Federico Caselli Date: Fri, 8 May 2026 20:48:58 +0000 (+0200) Subject: update to black 26.3.1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=c7e814b58440fa2d7cef61894abd3a512a4f8c92;p=thirdparty%2Fsqlalchemy%2Fsqlalchemy.git update to black 26.3.1 Closes: #13280 Change-Id: Ifbb77dd6d2a1c228ae97fcf8160f40e975edc57c (cherry picked from commit 1e1c0084b1804eaae8b7f089435241a2b8f4be60) --- diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index dfbc82115b..db28b56728 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,7 +2,7 @@ # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/python/black - rev: 25.11.0 + rev: 26.3.1 hooks: - id: black @@ -39,4 +39,4 @@ repos: types: [rst] exclude: README.* additional_dependencies: - - black==25.9.0 + - black==26.3.1 diff --git a/doc/build/changelog/migration_20.rst b/doc/build/changelog/migration_20.rst index 414291797a..7969c86c7b 100644 --- a/doc/build/changelog/migration_20.rst +++ b/doc/build/changelog/migration_20.rst @@ -209,7 +209,6 @@ Given the example program below:: from sqlalchemy import select from sqlalchemy import table - engine = create_engine("sqlite://") engine.execute("CREATE TABLE foo (id integer)") @@ -278,7 +277,6 @@ as a bonus our program is much clearer:: from sqlalchemy import table from sqlalchemy import text - engine = create_engine("sqlite://") # don't rely on autocommit for DML and DDL @@ -1245,7 +1243,6 @@ Code that works with classical mappings should change imports and code from:: from sqlalchemy.orm import mapper - mapper(SomeClass, some_table, properties={"related": relationship(SomeRelatedClass)}) To work from a central :class:`_orm.registry` object:: diff --git a/doc/build/core/connections.rst b/doc/build/core/connections.rst index cad79fa8a4..a8affc0a56 100644 --- a/doc/build/core/connections.rst +++ b/doc/build/core/connections.rst @@ -295,6 +295,7 @@ to as great a degree as possible. Setting Isolation Level or DBAPI Autocommit for a Connection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +..format: off For an individual :class:`_engine.Connection` object that's acquired from :meth:`.Engine.connect`, the isolation level can be set for the duration of @@ -313,6 +314,7 @@ are strings which are typically a subset of the following names:: Not every DBAPI supports every value; if an unsupported value is used for a certain backend, an error is raised. +..format: on For example, to force REPEATABLE READ on a specific connection, then begin a transaction:: @@ -2638,7 +2640,6 @@ the need for separate installation. Use the ``register()`` function as follows from sqlalchemy.dialects import registry - registry.register("mysql.foodialect", "myapp.dialect", "MyMySQLDialect") The above will respond to ``create_engine("mysql+foodialect://")`` and load the diff --git a/doc/build/faq/sqlexpressions.rst b/doc/build/faq/sqlexpressions.rst index e09fda4a27..632230b994 100644 --- a/doc/build/faq/sqlexpressions.rst +++ b/doc/build/faq/sqlexpressions.rst @@ -161,7 +161,6 @@ datatype:: from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import declarative_base - Base = declarative_base() diff --git a/doc/build/orm/dataclasses.rst b/doc/build/orm/dataclasses.rst index 532092ac9a..bd0b0372b1 100644 --- a/doc/build/orm/dataclasses.rst +++ b/doc/build/orm/dataclasses.rst @@ -102,7 +102,6 @@ decorator is supported:: from sqlalchemy.orm import mapped_column from sqlalchemy.orm import registry - reg = registry() @@ -121,7 +120,6 @@ have better compatibility with some versions of the mypy type checker:: from sqlalchemy.orm import mapped_column from sqlalchemy.orm import registry - reg = registry() @@ -172,7 +170,6 @@ the decorator directly:: from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column - reg = registry() diff --git a/doc/build/orm/declarative_tables.rst b/doc/build/orm/declarative_tables.rst index e4e7ca5cf6..44471c9aac 100644 --- a/doc/build/orm/declarative_tables.rst +++ b/doc/build/orm/declarative_tables.rst @@ -1088,7 +1088,6 @@ and ``required_name`` which is a :class:`.String` of length 30 that's from sqlalchemy import String from sqlalchemy.orm import mapped_column - intpk = Annotated[int, mapped_column(primary_key=True)] timestamp = Annotated[ datetime.datetime, @@ -2045,7 +2044,6 @@ map such a table as in the following example:: from sqlalchemy import UniqueConstraint from sqlalchemy.orm import DeclarativeBase - metadata = MetaData() group_users = Table( "group_users", diff --git a/examples/asyncio/basic.py b/examples/asyncio/basic.py index 5994fc765e..008d08507d 100644 --- a/examples/asyncio/basic.py +++ b/examples/asyncio/basic.py @@ -15,7 +15,6 @@ from sqlalchemy import String from sqlalchemy import Table from sqlalchemy.ext.asyncio import create_async_engine - meta = MetaData() t1 = Table( diff --git a/examples/custom_attributes/custom_management.py b/examples/custom_attributes/custom_management.py index da22ee3276..c87f3a62a5 100644 --- a/examples/custom_attributes/custom_management.py +++ b/examples/custom_attributes/custom_management.py @@ -26,7 +26,6 @@ from sqlalchemy.orm.attributes import get_attribute from sqlalchemy.orm.attributes import set_attribute from sqlalchemy.orm.instrumentation import is_instrumented - registry = _reg() diff --git a/examples/dogpile_caching/environment.py b/examples/dogpile_caching/environment.py index 4962826280..049b64a65d 100644 --- a/examples/dogpile_caching/environment.py +++ b/examples/dogpile_caching/environment.py @@ -14,7 +14,6 @@ from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker from . import caching_query - # dogpile cache regions. A home base for cache configurations. regions = {} diff --git a/examples/dogpile_caching/helloworld.py b/examples/dogpile_caching/helloworld.py index df1c2a318e..882c86ab3b 100644 --- a/examples/dogpile_caching/helloworld.py +++ b/examples/dogpile_caching/helloworld.py @@ -6,7 +6,6 @@ from .environment import cache from .environment import Session from .model import Person - # load Person objects. cache the result in the "default" cache region print("loading people....") people = Session.scalars(select(Person).options(FromCache("default"))).all() diff --git a/examples/dogpile_caching/relationship_caching.py b/examples/dogpile_caching/relationship_caching.py index a5b654b06c..37c519ba74 100644 --- a/examples/dogpile_caching/relationship_caching.py +++ b/examples/dogpile_caching/relationship_caching.py @@ -16,7 +16,6 @@ from .environment import Session from .model import cache_address_bits from .model import Person - for p in Session.scalars( select(Person).options(joinedload(Person.addresses), cache_address_bits) ).unique(): diff --git a/examples/graphs/directed_graph.py b/examples/graphs/directed_graph.py index d6611eaa79..b40dbe39df 100644 --- a/examples/graphs/directed_graph.py +++ b/examples/graphs/directed_graph.py @@ -8,7 +8,6 @@ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy.orm import sessionmaker - Base = declarative_base() diff --git a/examples/inheritance/concrete.py b/examples/inheritance/concrete.py index e718e2fc35..60b4c254d8 100644 --- a/examples/inheritance/concrete.py +++ b/examples/inheritance/concrete.py @@ -17,7 +17,6 @@ from sqlalchemy.orm import relationship from sqlalchemy.orm import Session from sqlalchemy.orm import with_polymorphic - intpk = Annotated[int, mapped_column(primary_key=True)] str50 = Annotated[str, mapped_column(String(50))] diff --git a/examples/inheritance/joined.py b/examples/inheritance/joined.py index c2ba6942cc..e2a6608d11 100644 --- a/examples/inheritance/joined.py +++ b/examples/inheritance/joined.py @@ -16,7 +16,6 @@ from sqlalchemy.orm import relationship from sqlalchemy.orm import Session from sqlalchemy.orm import with_polymorphic - intpk = Annotated[int, mapped_column(primary_key=True)] str50 = Annotated[str, mapped_column(String(50))] diff --git a/examples/materialized_paths/materialized_paths.py b/examples/materialized_paths/materialized_paths.py index 19d3ed491c..fdb206f2df 100644 --- a/examples/materialized_paths/materialized_paths.py +++ b/examples/materialized_paths/materialized_paths.py @@ -41,7 +41,6 @@ from sqlalchemy.orm import remote from sqlalchemy.orm import Session from sqlalchemy.sql.expression import cast - Base = declarative_base() diff --git a/examples/nested_sets/nested_sets.py b/examples/nested_sets/nested_sets.py index 1492f6abd8..f34b99e7c7 100644 --- a/examples/nested_sets/nested_sets.py +++ b/examples/nested_sets/nested_sets.py @@ -16,7 +16,6 @@ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import aliased from sqlalchemy.orm import Session - Base = declarative_base() diff --git a/examples/performance/__main__.py b/examples/performance/__main__.py index aeb124e1d1..945458651a 100644 --- a/examples/performance/__main__.py +++ b/examples/performance/__main__.py @@ -2,6 +2,5 @@ from . import Profiler - if __name__ == "__main__": Profiler.main() diff --git a/examples/performance/bulk_updates.py b/examples/performance/bulk_updates.py index de5e6dc27d..345d1e066f 100644 --- a/examples/performance/bulk_updates.py +++ b/examples/performance/bulk_updates.py @@ -13,7 +13,6 @@ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Session from . import Profiler - Base = declarative_base() engine = None diff --git a/examples/performance/large_resultsets.py b/examples/performance/large_resultsets.py index 3617141127..4ec8822d82 100644 --- a/examples/performance/large_resultsets.py +++ b/examples/performance/large_resultsets.py @@ -24,7 +24,6 @@ from sqlalchemy.orm import Bundle from sqlalchemy.orm import Session from . import Profiler - Base = declarative_base() engine = None diff --git a/examples/performance/short_selects.py b/examples/performance/short_selects.py index 6ff187bf0f..403316d4e4 100644 --- a/examples/performance/short_selects.py +++ b/examples/performance/short_selects.py @@ -19,7 +19,6 @@ from sqlalchemy.orm import deferred from sqlalchemy.orm import Session from . import Profiler - Base = declarative_base() engine = None diff --git a/examples/performance/single_inserts.py b/examples/performance/single_inserts.py index 4b8132c50a..d6c38c22ba 100644 --- a/examples/performance/single_inserts.py +++ b/examples/performance/single_inserts.py @@ -16,7 +16,6 @@ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Session from . import Profiler - Base = declarative_base() engine = None diff --git a/examples/sharding/asyncio.py b/examples/sharding/asyncio.py index a63b0fcaaa..09047f2fc0 100644 --- a/examples/sharding/asyncio.py +++ b/examples/sharding/asyncio.py @@ -32,7 +32,6 @@ from sqlalchemy.orm import relationship from sqlalchemy.sql import operators from sqlalchemy.sql import visitors - echo = True db1 = create_async_engine("sqlite+aiosqlite://", echo=echo) db2 = create_async_engine("sqlite+aiosqlite://", echo=echo) diff --git a/examples/sharding/separate_databases.py b/examples/sharding/separate_databases.py index 9a700734c5..b327b2e15c 100644 --- a/examples/sharding/separate_databases.py +++ b/examples/sharding/separate_databases.py @@ -21,7 +21,6 @@ from sqlalchemy.orm import sessionmaker from sqlalchemy.sql import operators from sqlalchemy.sql import visitors - echo = True db1 = create_engine("sqlite://", echo=echo) db2 = create_engine("sqlite://", echo=echo) diff --git a/examples/sharding/separate_schema_translates.py b/examples/sharding/separate_schema_translates.py index fd754356e5..e8683bfe85 100644 --- a/examples/sharding/separate_schema_translates.py +++ b/examples/sharding/separate_schema_translates.py @@ -22,7 +22,6 @@ from sqlalchemy.orm import mapped_column from sqlalchemy.orm import relationship from sqlalchemy.orm import sessionmaker - echo = True engine = create_engine("sqlite://", echo=echo) diff --git a/examples/space_invaders/space_invaders.py b/examples/space_invaders/space_invaders.py index 5ad59db8f3..1029db8e9a 100644 --- a/examples/space_invaders/space_invaders.py +++ b/examples/space_invaders/space_invaders.py @@ -18,7 +18,6 @@ from sqlalchemy.orm import joinedload from sqlalchemy.orm import relationship from sqlalchemy.orm import Session - logging.basicConfig( filename="space_invaders.log", format="%(asctime)s,%(msecs)03d %(levelname)-5.5s %(message)s", diff --git a/examples/versioned_rows/versioned_update_old_row.py b/examples/versioned_rows/versioned_update_old_row.py index e4c45b9508..4bd1d6d8d0 100644 --- a/examples/versioned_rows/versioned_update_old_row.py +++ b/examples/versioned_rows/versioned_update_old_row.py @@ -25,7 +25,6 @@ from sqlalchemy.orm import relationship from sqlalchemy.orm import Session from sqlalchemy.orm import with_loader_criteria - Base = declarative_base() # this will be the current time as the test runs diff --git a/lib/sqlalchemy/connectors/aioodbc.py b/lib/sqlalchemy/connectors/aioodbc.py index ccc1c77b44..44df0a9c47 100644 --- a/lib/sqlalchemy/connectors/aioodbc.py +++ b/lib/sqlalchemy/connectors/aioodbc.py @@ -20,7 +20,6 @@ from .. import util from ..util.concurrency import await_fallback from ..util.concurrency import await_only - if TYPE_CHECKING: from ..engine.interfaces import ConnectArgsType from ..engine.url import URL diff --git a/lib/sqlalchemy/dialects/_typing.py b/lib/sqlalchemy/dialects/_typing.py index bf9b67a0a0..aef755d18e 100644 --- a/lib/sqlalchemy/dialects/_typing.py +++ b/lib/sqlalchemy/dialects/_typing.py @@ -18,7 +18,6 @@ from ..sql.schema import Column from ..sql.schema import ColumnCollectionConstraint from ..sql.schema import Index - _OnConflictConstraintT = Union[str, ColumnCollectionConstraint, Index, None] _OnConflictIndexElementsT = Optional[ Iterable[Union[Column[Any], str, roles.DDLConstraintColumnRole]] diff --git a/lib/sqlalchemy/dialects/mssql/__init__.py b/lib/sqlalchemy/dialects/mssql/__init__.py index 68d1d7c744..ababcc138f 100644 --- a/lib/sqlalchemy/dialects/mssql/__init__.py +++ b/lib/sqlalchemy/dialects/mssql/__init__.py @@ -45,7 +45,6 @@ from .base import VARCHAR from .base import XML from ...sql import try_cast - base.dialect = dialect = pyodbc.dialect diff --git a/lib/sqlalchemy/dialects/mssql/base.py b/lib/sqlalchemy/dialects/mssql/base.py index fd1dd997c9..9d718b057a 100644 --- a/lib/sqlalchemy/dialects/mssql/base.py +++ b/lib/sqlalchemy/dialects/mssql/base.py @@ -3220,8 +3220,7 @@ class MSDialect(default.DefaultDialect): view_name = f"sys.{row[0]}" - cursor.execute( - """ + cursor.execute(""" SELECT CASE transaction_isolation_level WHEN 0 THEN NULL WHEN 1 THEN 'READ UNCOMMITTED' @@ -3232,10 +3231,7 @@ class MSDialect(default.DefaultDialect): AS TRANSACTION_ISOLATION_LEVEL FROM {} where session_id = @@SPID - """.format( - view_name - ) - ) + """.format(view_name)) except self.dbapi.Error as err: raise NotImplementedError( "Can't fetch isolation level; encountered error {} when " @@ -3432,8 +3428,7 @@ class MSDialect(default.DefaultDialect): else "NULL as filter_definition" ) rp = connection.execution_options(future_result=True).execute( - sql.text( - f""" + sql.text(f""" select ind.index_id, ind.is_unique, @@ -3453,8 +3448,7 @@ where and ind.type != 0 order by ind.name - """ - ) + """) .bindparams( sql.bindparam("tabname", tablename, ischema.CoerceUnicode()), sql.bindparam("schname", owner, ischema.CoerceUnicode()), @@ -3482,8 +3476,7 @@ order by do["mssql_where"] = row["filter_definition"] rp = connection.execution_options(future_result=True).execute( - sql.text( - """ + sql.text(""" select ind_col.index_id, col.name, @@ -3503,8 +3496,7 @@ where order by ind_col.index_id, ind_col.key_ordinal - """ - ) + """) .bindparams( sql.bindparam("tabname", tablename, ischema.CoerceUnicode()), sql.bindparam("schname", owner, ischema.CoerceUnicode()), @@ -3930,8 +3922,7 @@ order by ): # Foreign key constraints s = ( - text( - """\ + text("""\ WITH fk_info AS ( SELECT ischema_ref_con.constraint_schema, @@ -4031,8 +4022,7 @@ index_info AS ( ORDER BY fk_info.constraint_schema, fk_info.constraint_name, fk_info.ordinal_position -""" - ) +""") .bindparams( sql.bindparam("tablename", tablename, ischema.CoerceUnicode()), sql.bindparam("owner", owner, ischema.CoerceUnicode()), diff --git a/lib/sqlalchemy/dialects/mssql/information_schema.py b/lib/sqlalchemy/dialects/mssql/information_schema.py index d739d71823..5249f3e39f 100644 --- a/lib/sqlalchemy/dialects/mssql/information_schema.py +++ b/lib/sqlalchemy/dialects/mssql/information_schema.py @@ -20,7 +20,6 @@ from ...types import String from ...types import TypeDecorator from ...types import Unicode - ischema = MetaData() diff --git a/lib/sqlalchemy/dialects/mssql/pymssql.py b/lib/sqlalchemy/dialects/mssql/pymssql.py index 7244bb0d3e..6c6c3a2e74 100644 --- a/lib/sqlalchemy/dialects/mssql/pymssql.py +++ b/lib/sqlalchemy/dialects/mssql/pymssql.py @@ -22,6 +22,7 @@ pymssql is a Python module that provides a Python DBAPI interface around """ # noqa + import re from .base import MSDialect diff --git a/lib/sqlalchemy/dialects/mssql/pyodbc.py b/lib/sqlalchemy/dialects/mssql/pyodbc.py index 5d3ae0b13f..874cc70a4e 100644 --- a/lib/sqlalchemy/dialects/mssql/pyodbc.py +++ b/lib/sqlalchemy/dialects/mssql/pyodbc.py @@ -359,7 +359,6 @@ hook. See that method for usage examples. """ # noqa - import datetime import decimal import re diff --git a/lib/sqlalchemy/dialects/mysql/aiomysql.py b/lib/sqlalchemy/dialects/mysql/aiomysql.py index 7e68c61dac..55ef60796c 100644 --- a/lib/sqlalchemy/dialects/mysql/aiomysql.py +++ b/lib/sqlalchemy/dialects/mysql/aiomysql.py @@ -28,6 +28,7 @@ This dialect should normally be used only with the ) """ # noqa + from __future__ import annotations from types import ModuleType diff --git a/lib/sqlalchemy/dialects/mysql/asyncmy.py b/lib/sqlalchemy/dialects/mysql/asyncmy.py index 5757476175..0006eec5b5 100644 --- a/lib/sqlalchemy/dialects/mysql/asyncmy.py +++ b/lib/sqlalchemy/dialects/mysql/asyncmy.py @@ -26,6 +26,7 @@ This dialect should normally be used only with the ) """ # noqa + from __future__ import annotations from types import ModuleType diff --git a/lib/sqlalchemy/dialects/mysql/base.py b/lib/sqlalchemy/dialects/mysql/base.py index 3c84e36fd3..506f2f2840 100644 --- a/lib/sqlalchemy/dialects/mysql/base.py +++ b/lib/sqlalchemy/dialects/mysql/base.py @@ -1063,6 +1063,7 @@ output: ) """ # noqa + from __future__ import annotations from collections import defaultdict @@ -3254,7 +3255,7 @@ class MySQLDialect(default.DefaultDialect): def _is_mariadb_102(self) -> bool: return ( self.is_mariadb - and self._mariadb_normalized_version_info # type:ignore[operator] + and self._mariadb_normalized_version_info # type: ignore[operator] > ( 10, 2, diff --git a/lib/sqlalchemy/dialects/mysql/cymysql.py b/lib/sqlalchemy/dialects/mysql/cymysql.py index 325d3321e3..cc3c2a8bc8 100644 --- a/lib/sqlalchemy/dialects/mysql/cymysql.py +++ b/lib/sqlalchemy/dialects/mysql/cymysql.py @@ -20,6 +20,7 @@ r""" dialects are mysqlclient and PyMySQL. """ # noqa + from __future__ import annotations from typing import Any diff --git a/lib/sqlalchemy/dialects/mysql/dml.py b/lib/sqlalchemy/dialects/mysql/dml.py index d5bbf14bb8..b76041226f 100644 --- a/lib/sqlalchemy/dialects/mysql/dml.py +++ b/lib/sqlalchemy/dialects/mysql/dml.py @@ -28,7 +28,6 @@ from ...sql.expression import alias from ...sql.selectable import NamedFromClause from ...util.typing import Self - __all__ = ("Insert", "insert") diff --git a/lib/sqlalchemy/dialects/mysql/mariadbconnector.py b/lib/sqlalchemy/dialects/mysql/mariadbconnector.py index bd5d7a2584..5e78da4056 100644 --- a/lib/sqlalchemy/dialects/mysql/mariadbconnector.py +++ b/lib/sqlalchemy/dialects/mysql/mariadbconnector.py @@ -27,6 +27,7 @@ be ``mysqldb``. ``mariadb+mariadbconnector://`` is required to use this driver. .. mariadb: https://github.com/mariadb-corporation/mariadb-connector-python """ # noqa + from __future__ import annotations import re diff --git a/lib/sqlalchemy/dialects/mysql/mysqlconnector.py b/lib/sqlalchemy/dialects/mysql/mysqlconnector.py index d97dbe2195..1cc0c9e08d 100644 --- a/lib/sqlalchemy/dialects/mysql/mysqlconnector.py +++ b/lib/sqlalchemy/dialects/mysql/mysqlconnector.py @@ -45,6 +45,7 @@ charset/collation will allow connectivity. """ # noqa + from __future__ import annotations import re @@ -110,8 +111,8 @@ class IdentifierPreparerCommon_mysqlconnector: def _escape_identifier(self, value: str) -> str: value = value.replace( - self.escape_quote, # type:ignore[attr-defined] - self.escape_to_quote, # type:ignore[attr-defined] + self.escape_quote, # type: ignore[attr-defined] + self.escape_to_quote, # type: ignore[attr-defined] ) return value diff --git a/lib/sqlalchemy/dialects/mysql/mysqldb.py b/lib/sqlalchemy/dialects/mysql/mysqldb.py index 188668be79..60fa3821db 100644 --- a/lib/sqlalchemy/dialects/mysql/mysqldb.py +++ b/lib/sqlalchemy/dialects/mysql/mysqldb.py @@ -84,6 +84,7 @@ Server Side Cursors The mysqldb dialect supports server-side cursors. See :ref:`mysql_ss_cursors`. """ + from __future__ import annotations import re diff --git a/lib/sqlalchemy/dialects/mysql/pymysql.py b/lib/sqlalchemy/dialects/mysql/pymysql.py index ae86938e65..e297da254f 100644 --- a/lib/sqlalchemy/dialects/mysql/pymysql.py +++ b/lib/sqlalchemy/dialects/mysql/pymysql.py @@ -47,6 +47,7 @@ and targets 100% compatibility. Most behavioral notes for MySQL-python apply to the pymysql driver as well. """ # noqa + from __future__ import annotations from typing import Any diff --git a/lib/sqlalchemy/dialects/mysql/pyodbc.py b/lib/sqlalchemy/dialects/mysql/pyodbc.py index bb37ff0e59..023c17682f 100644 --- a/lib/sqlalchemy/dialects/mysql/pyodbc.py +++ b/lib/sqlalchemy/dialects/mysql/pyodbc.py @@ -42,6 +42,7 @@ Pass through exact pyodbc connection string:: connection_uri = "mysql+pyodbc:///?odbc_connect=%s" % params """ # noqa + from __future__ import annotations import datetime diff --git a/lib/sqlalchemy/dialects/mysql/reflection.py b/lib/sqlalchemy/dialects/mysql/reflection.py index df0b88ebb0..0ceda89f2a 100644 --- a/lib/sqlalchemy/dialects/mysql/reflection.py +++ b/lib/sqlalchemy/dialects/mysql/reflection.py @@ -371,7 +371,7 @@ class MySQLTableDefinitionParser: buffer = [] for row in columns: - (name, col_type, nullable, default, extra) = ( + name, col_type, nullable, default, extra = ( row[i] for i in (0, 1, 2, 4, 5) ) diff --git a/lib/sqlalchemy/dialects/oracle/cx_oracle.py b/lib/sqlalchemy/dialects/oracle/cx_oracle.py index 8750354c9a..2dc823d47d 100644 --- a/lib/sqlalchemy/dialects/oracle/cx_oracle.py +++ b/lib/sqlalchemy/dialects/oracle/cx_oracle.py @@ -489,6 +489,7 @@ SQLAlchemy type (or a subclass of such). as better integration of outputtypehandlers. """ # noqa + from __future__ import annotations import decimal diff --git a/lib/sqlalchemy/dialects/oracle/oracledb.py b/lib/sqlalchemy/dialects/oracle/oracledb.py index a41f6be87f..abe8e571fd 100644 --- a/lib/sqlalchemy/dialects/oracle/oracledb.py +++ b/lib/sqlalchemy/dialects/oracle/oracledb.py @@ -588,6 +588,7 @@ SQLAlchemy type (or a subclass of such). .. versionadded:: 2.0.0 added support for the python-oracledb driver. """ # noqa + from __future__ import annotations import collections diff --git a/lib/sqlalchemy/dialects/oracle/vector.py b/lib/sqlalchemy/dialects/oracle/vector.py index 53057675ba..ac1c9b0401 100644 --- a/lib/sqlalchemy/dialects/oracle/vector.py +++ b/lib/sqlalchemy/dialects/oracle/vector.py @@ -313,12 +313,10 @@ class VECTOR(types.TypeEngine): ) else: - raise TypeError( - """ + raise TypeError(""" Invalid input for VECTOR: expected a list, an array.array, or a SparseVector object. - """ - ) + """) return process diff --git a/lib/sqlalchemy/dialects/postgresql/__init__.py b/lib/sqlalchemy/dialects/postgresql/__init__.py index a94cfef2c6..e1900ec9bd 100644 --- a/lib/sqlalchemy/dialects/postgresql/__init__.py +++ b/lib/sqlalchemy/dialects/postgresql/__init__.py @@ -89,7 +89,6 @@ from .types import TIMESTAMP from .types import TSQUERY from .types import TSVECTOR - # Alias psycopg also as psycopg_async psycopg_async = type( "psycopg_async", (ModuleType,), {"dialect": psycopg.dialect_async} diff --git a/lib/sqlalchemy/dialects/postgresql/dml.py b/lib/sqlalchemy/dialects/postgresql/dml.py index 053770e1c8..6eea13179d 100644 --- a/lib/sqlalchemy/dialects/postgresql/dml.py +++ b/lib/sqlalchemy/dialects/postgresql/dml.py @@ -35,7 +35,6 @@ from ...sql.elements import TextClause from ...sql.expression import alias from ...util.typing import Self - __all__ = ("Insert", "insert") diff --git a/lib/sqlalchemy/dialects/postgresql/hstore.py b/lib/sqlalchemy/dialects/postgresql/hstore.py index 27005f0639..66ad484257 100644 --- a/lib/sqlalchemy/dialects/postgresql/hstore.py +++ b/lib/sqlalchemy/dialects/postgresql/hstore.py @@ -19,7 +19,6 @@ from .operators import HAS_KEY from ... import types as sqltypes from ...sql import functions as sqlfunc - __all__ = ("HSTORE", "hstore") diff --git a/lib/sqlalchemy/dialects/postgresql/operators.py b/lib/sqlalchemy/dialects/postgresql/operators.py index 9e4d26570e..d38d0160b4 100644 --- a/lib/sqlalchemy/dialects/postgresql/operators.py +++ b/lib/sqlalchemy/dialects/postgresql/operators.py @@ -7,7 +7,6 @@ # mypy: ignore-errors from ...sql import operators - _getitem_precedence = operators._PRECEDENCE[operators.json_getitem_op] _eq_precedence = operators._PRECEDENCE[operators.eq] diff --git a/lib/sqlalchemy/dialects/postgresql/pg8000.py b/lib/sqlalchemy/dialects/postgresql/pg8000.py index cd233de135..faee3414fd 100644 --- a/lib/sqlalchemy/dialects/postgresql/pg8000.py +++ b/lib/sqlalchemy/dialects/postgresql/pg8000.py @@ -95,6 +95,7 @@ of the :ref:`psycopg2 ` dialect: """ # noqa + import decimal import re @@ -587,11 +588,8 @@ class PGDialect_pg8000(PGDialect): def _set_client_encoding(self, dbapi_connection, client_encoding): cursor = dbapi_connection.cursor() - cursor.execute( - f"""SET CLIENT_ENCODING TO '{ - client_encoding.replace("'", "''") - }'""" - ) + cursor.execute(f""" + SET CLIENT_ENCODING TO '{client_encoding.replace("'", "''")}'""") cursor.execute("COMMIT") cursor.close() diff --git a/lib/sqlalchemy/dialects/postgresql/psycopg.py b/lib/sqlalchemy/dialects/postgresql/psycopg.py index 4af214dabb..4b8d4e8ee9 100644 --- a/lib/sqlalchemy/dialects/postgresql/psycopg.py +++ b/lib/sqlalchemy/dialects/postgresql/psycopg.py @@ -168,6 +168,7 @@ specified:: `Client-side-binding cursors `_ """ # noqa + from __future__ import annotations from collections import deque diff --git a/lib/sqlalchemy/dialects/postgresql/psycopg2.py b/lib/sqlalchemy/dialects/postgresql/psycopg2.py index 48ed9bf1e1..e56eb6d6da 100644 --- a/lib/sqlalchemy/dialects/postgresql/psycopg2.py +++ b/lib/sqlalchemy/dialects/postgresql/psycopg2.py @@ -488,6 +488,7 @@ place within SQLAlchemy's own marshalling logic, and not that of ``psycopg2`` which may be more performant. """ # noqa + from __future__ import annotations import collections.abc as collections_abc diff --git a/lib/sqlalchemy/dialects/postgresql/psycopg2cffi.py b/lib/sqlalchemy/dialects/postgresql/psycopg2cffi.py index f4dcfc7014..cfad97a69c 100644 --- a/lib/sqlalchemy/dialects/postgresql/psycopg2cffi.py +++ b/lib/sqlalchemy/dialects/postgresql/psycopg2cffi.py @@ -22,6 +22,7 @@ is as per ``psycopg2``. :mod:`sqlalchemy.dialects.postgresql.psycopg2` """ # noqa + from .psycopg2 import PGDialect_psycopg2 from ... import util diff --git a/lib/sqlalchemy/dialects/sqlite/aiosqlite.py b/lib/sqlalchemy/dialects/sqlite/aiosqlite.py index afd3688edc..4cb4a2c319 100644 --- a/lib/sqlalchemy/dialects/sqlite/aiosqlite.py +++ b/lib/sqlalchemy/dialects/sqlite/aiosqlite.py @@ -77,6 +77,7 @@ based on the kind of SQLite database that's requested: :paramref:`_sa.create_engine.poolclass` parameter. """ # noqa + from __future__ import annotations import asyncio diff --git a/lib/sqlalchemy/dialects/sqlite/base.py b/lib/sqlalchemy/dialects/sqlite/base.py index d9f5756755..be388a5146 100644 --- a/lib/sqlalchemy/dialects/sqlite/base.py +++ b/lib/sqlalchemy/dialects/sqlite/base.py @@ -847,13 +847,11 @@ The bug, entirely outside of SQLAlchemy, can be illustrated thusly:: cursor.execute("select x.a, x.b from x") assert [c[0] for c in cursor.description] == ["a", "b"] - cursor.execute( - """ + cursor.execute(""" select x.a, x.b from x where a=1 union select x.a, x.b from x where a=2 - """ - ) + """) assert [c[0] for c in cursor.description] == ["a", "b"], [ c[0] for c in cursor.description ] @@ -888,13 +886,11 @@ to filter these out:: result = conn.exec_driver_sql("select x.a, x.b from x") assert result.keys() == ["a", "b"] - result = conn.exec_driver_sql( - """ + result = conn.exec_driver_sql(""" select x.a, x.b from x where a=1 union select x.a, x.b from x where a=2 - """ - ) + """) assert result.keys() == ["a", "b"] Note that above, even though SQLAlchemy filters out the dots, *both @@ -987,6 +983,7 @@ passed to methods such as :meth:`_schema.MetaData.reflect` or documentation. ''' # noqa + from __future__ import annotations import datetime @@ -2582,7 +2579,7 @@ class SQLiteDialect(default.DefaultDialect): fks = {} for row in pragma_fks: - (numerical_id, rtbl, lcol, rcol) = (row[0], row[2], row[3], row[4]) + numerical_id, rtbl, lcol, rcol = (row[0], row[2], row[3], row[4]) if not rcol: # no referred column, which means it was not named in the diff --git a/lib/sqlalchemy/dialects/sqlite/pysqlite.py b/lib/sqlalchemy/dialects/sqlite/pysqlite.py index d2e84466c9..54fa940a77 100644 --- a/lib/sqlalchemy/dialects/sqlite/pysqlite.py +++ b/lib/sqlalchemy/dialects/sqlite/pysqlite.py @@ -392,6 +392,7 @@ connection when it is created. That is accomplished with an event listener:: print(conn.scalar(text("SELECT UDF()"))) """ # noqa + from __future__ import annotations import math diff --git a/lib/sqlalchemy/engine/_py_processors.py b/lib/sqlalchemy/engine/_py_processors.py index 7b1d6b0db2..11c7ef01c5 100644 --- a/lib/sqlalchemy/engine/_py_processors.py +++ b/lib/sqlalchemy/engine/_py_processors.py @@ -28,7 +28,6 @@ from typing import Type from typing import TypeVar from typing import Union - _DT = TypeVar( "_DT", bound=Union[datetime.datetime, datetime.time, datetime.date] ) diff --git a/lib/sqlalchemy/engine/base.py b/lib/sqlalchemy/engine/base.py index e3b71fe5b5..af313b8782 100644 --- a/lib/sqlalchemy/engine/base.py +++ b/lib/sqlalchemy/engine/base.py @@ -5,6 +5,7 @@ # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php """Defines :class:`_engine.Connection` and :class:`_engine.Engine`.""" + from __future__ import annotations import contextlib diff --git a/lib/sqlalchemy/engine/create.py b/lib/sqlalchemy/engine/create.py index 9ab94763b0..dee77dab43 100644 --- a/lib/sqlalchemy/engine/create.py +++ b/lib/sqlalchemy/engine/create.py @@ -630,7 +630,7 @@ def create_engine(url: Union[str, _url.URL], **kwargs: Any) -> Engine: dialect = dialect_cls(**dialect_args) # assemble connection arguments - (cargs_tup, _cparams) = dialect.create_connect_args(u) + cargs_tup, _cparams = dialect.create_connect_args(u) cparams = util.immutabledict(_cparams).union(pop_kwarg("connect_args", {})) if "async_fallback" in cparams and util.asbool(cparams["async_fallback"]): diff --git a/lib/sqlalchemy/engine/cursor.py b/lib/sqlalchemy/engine/cursor.py index 5da66febb1..15ae1d0c74 100644 --- a/lib/sqlalchemy/engine/cursor.py +++ b/lib/sqlalchemy/engine/cursor.py @@ -8,7 +8,6 @@ """Define cursor-specific result set constructs including :class:`.CursorResult`.""" - from __future__ import annotations import collections @@ -56,7 +55,6 @@ from ..util.typing import Final from ..util.typing import Literal from ..util.typing import Self - if typing.TYPE_CHECKING: from .base import Connection from .default import DefaultExecutionContext diff --git a/lib/sqlalchemy/engine/mock.py b/lib/sqlalchemy/engine/mock.py index a5173b9d7d..adcf6eb367 100644 --- a/lib/sqlalchemy/engine/mock.py +++ b/lib/sqlalchemy/engine/mock.py @@ -19,7 +19,6 @@ from typing import Union from . import url as _url from .. import util - if typing.TYPE_CHECKING: from .base import Engine from .interfaces import _CoreAnyExecuteParams diff --git a/lib/sqlalchemy/engine/processors.py b/lib/sqlalchemy/engine/processors.py index 0888257f20..aa854aa699 100644 --- a/lib/sqlalchemy/engine/processors.py +++ b/lib/sqlalchemy/engine/processors.py @@ -12,6 +12,7 @@ processors. They all share one common characteristic: None is passed through unchanged. """ + from __future__ import annotations import typing diff --git a/lib/sqlalchemy/engine/reflection.py b/lib/sqlalchemy/engine/reflection.py index c976ae0f13..b3659acf9a 100644 --- a/lib/sqlalchemy/engine/reflection.py +++ b/lib/sqlalchemy/engine/reflection.py @@ -24,6 +24,7 @@ methods such as get_table_names, get_columns, etc. use the key 'name'. So for most return values, each record will have a 'name' attribute.. """ + from __future__ import annotations import contextlib diff --git a/lib/sqlalchemy/event/api.py b/lib/sqlalchemy/event/api.py index 38b2716b88..2f8547df51 100644 --- a/lib/sqlalchemy/event/api.py +++ b/lib/sqlalchemy/event/api.py @@ -6,6 +6,7 @@ # the MIT License: https://www.opensource.org/licenses/mit-license.php """Public API functions for the event system.""" + from __future__ import annotations from typing import Any @@ -18,7 +19,6 @@ from .registry import _ListenerFnType from .. import exc from .. import util - CANCEL = util.symbol("CANCEL") NO_RETVAL = util.symbol("NO_RETVAL") diff --git a/lib/sqlalchemy/event/attr.py b/lib/sqlalchemy/event/attr.py index e09cb4d5a4..2727bfaa57 100644 --- a/lib/sqlalchemy/event/attr.py +++ b/lib/sqlalchemy/event/attr.py @@ -28,6 +28,7 @@ as well as support for subclass propagation (e.g. events assigned to ``Pool`` vs. ``QueuePool``) are all implemented here. """ + from __future__ import annotations import collections diff --git a/lib/sqlalchemy/event/base.py b/lib/sqlalchemy/event/base.py index 9f6e410d68..239e4d7614 100644 --- a/lib/sqlalchemy/event/base.py +++ b/lib/sqlalchemy/event/base.py @@ -15,6 +15,7 @@ at the class level of a particular ``_Dispatch`` class as well as within instances of ``_Dispatch``. """ + from __future__ import annotations import typing diff --git a/lib/sqlalchemy/event/legacy.py b/lib/sqlalchemy/event/legacy.py index 63fc1ee9a9..b2fc4ca701 100644 --- a/lib/sqlalchemy/event/legacy.py +++ b/lib/sqlalchemy/event/legacy.py @@ -9,6 +9,7 @@ generation of deprecation notes and docstrings. """ + from __future__ import annotations import typing diff --git a/lib/sqlalchemy/event/registry.py b/lib/sqlalchemy/event/registry.py index 22be5628e4..a6b07c24b7 100644 --- a/lib/sqlalchemy/event/registry.py +++ b/lib/sqlalchemy/event/registry.py @@ -14,6 +14,7 @@ membership in all those collections can be revoked at once, based on an equivalent :class:`._EventKey`. """ + from __future__ import annotations import collections diff --git a/lib/sqlalchemy/exc.py b/lib/sqlalchemy/exc.py index c31c16b4dc..ed928eaab3 100644 --- a/lib/sqlalchemy/exc.py +++ b/lib/sqlalchemy/exc.py @@ -12,6 +12,7 @@ raised as a result of DBAPI exceptions are all subclasses of :exc:`.DBAPIError`. """ + from __future__ import annotations import typing diff --git a/lib/sqlalchemy/ext/__init__.py b/lib/sqlalchemy/ext/__init__.py index 5d61ac7652..a72b4aec5e 100644 --- a/lib/sqlalchemy/ext/__init__.py +++ b/lib/sqlalchemy/ext/__init__.py @@ -7,5 +7,4 @@ from .. import util as _sa_util - _sa_util.preloaded.import_prefix("sqlalchemy.ext") diff --git a/lib/sqlalchemy/ext/associationproxy.py b/lib/sqlalchemy/ext/associationproxy.py index 5fbabe578c..c1f0cc8bb3 100644 --- a/lib/sqlalchemy/ext/associationproxy.py +++ b/lib/sqlalchemy/ext/associationproxy.py @@ -13,6 +13,7 @@ transparent proxied access to the endpoint of an association object. See the example ``examples/association/proxied_association.py``. """ + from __future__ import annotations import operator diff --git a/lib/sqlalchemy/ext/asyncio/engine.py b/lib/sqlalchemy/ext/asyncio/engine.py index 263bd75cf4..57d6fcc6f4 100644 --- a/lib/sqlalchemy/ext/asyncio/engine.py +++ b/lib/sqlalchemy/ext/asyncio/engine.py @@ -187,7 +187,7 @@ class AsyncConnectable: ], ) # "Class has incompatible disjoint bases" - no idea -class AsyncConnection( # type:ignore[misc] +class AsyncConnection( # type: ignore[misc] ProxyComparable[Connection], StartableContext["AsyncConnection"], AsyncConnectable, diff --git a/lib/sqlalchemy/ext/asyncio/session.py b/lib/sqlalchemy/ext/asyncio/session.py index c547b9781e..003954b4a7 100644 --- a/lib/sqlalchemy/ext/asyncio/session.py +++ b/lib/sqlalchemy/ext/asyncio/session.py @@ -41,7 +41,6 @@ from ...util.concurrency import greenlet_spawn from ...util.typing import Concatenate from ...util.typing import ParamSpec - if TYPE_CHECKING: from .engine import AsyncConnection from .engine import AsyncEngine diff --git a/lib/sqlalchemy/ext/automap.py b/lib/sqlalchemy/ext/automap.py index a810b82e89..289ef1915e 100644 --- a/lib/sqlalchemy/ext/automap.py +++ b/lib/sqlalchemy/ext/automap.py @@ -710,6 +710,7 @@ be applied as:: """ # noqa + from __future__ import annotations import dataclasses diff --git a/lib/sqlalchemy/ext/baked.py b/lib/sqlalchemy/ext/baked.py index 2377c7d12a..da9acd1431 100644 --- a/lib/sqlalchemy/ext/baked.py +++ b/lib/sqlalchemy/ext/baked.py @@ -28,7 +28,6 @@ from ..sql import func from ..sql import literal_column from ..sql import util as sql_util - log = logging.getLogger(__name__) diff --git a/lib/sqlalchemy/ext/compiler.py b/lib/sqlalchemy/ext/compiler.py index 2de5001ee4..1c10ba423d 100644 --- a/lib/sqlalchemy/ext/compiler.py +++ b/lib/sqlalchemy/ext/compiler.py @@ -481,6 +481,7 @@ Example usage:: ) """ + from __future__ import annotations from typing import Any diff --git a/lib/sqlalchemy/ext/declarative/extensions.py b/lib/sqlalchemy/ext/declarative/extensions.py index d119aaebe1..d2a8d8b09d 100644 --- a/lib/sqlalchemy/ext/declarative/extensions.py +++ b/lib/sqlalchemy/ext/declarative/extensions.py @@ -8,6 +8,7 @@ """Public API functions and helpers for declarative.""" + from __future__ import annotations import collections diff --git a/lib/sqlalchemy/ext/horizontal_shard.py b/lib/sqlalchemy/ext/horizontal_shard.py index 4722353f3b..e0bb658f86 100644 --- a/lib/sqlalchemy/ext/horizontal_shard.py +++ b/lib/sqlalchemy/ext/horizontal_shard.py @@ -23,6 +23,7 @@ the source distribution. """ + from __future__ import annotations from typing import Any diff --git a/lib/sqlalchemy/ext/instrumentation.py b/lib/sqlalchemy/ext/instrumentation.py index 08d55dbdb7..79c83f8f4f 100644 --- a/lib/sqlalchemy/ext/instrumentation.py +++ b/lib/sqlalchemy/ext/instrumentation.py @@ -23,6 +23,7 @@ For examples of how the instrumentation extension is used, see the example :ref:`examples_instrumentation`. """ + import weakref from .. import util @@ -39,7 +40,6 @@ from ..orm.instrumentation import _default_state_getter from ..orm.instrumentation import ClassManager from ..orm.instrumentation import InstrumentationFactory - INSTRUMENTATION_MANAGER = "__sa_instrumentation_manager__" """Attribute, elects custom instrumentation when present on a mapped class. diff --git a/lib/sqlalchemy/ext/mypy/plugin.py b/lib/sqlalchemy/ext/mypy/plugin.py index 73b0d6d26e..fe2ab07a6c 100644 --- a/lib/sqlalchemy/ext/mypy/plugin.py +++ b/lib/sqlalchemy/ext/mypy/plugin.py @@ -9,6 +9,7 @@ Mypy plugin for SQLAlchemy ORM. """ + from __future__ import annotations from typing import Callable diff --git a/lib/sqlalchemy/ext/orderinglist.py b/lib/sqlalchemy/ext/orderinglist.py index fcd483cf5f..489a3eff24 100644 --- a/lib/sqlalchemy/ext/orderinglist.py +++ b/lib/sqlalchemy/ext/orderinglist.py @@ -126,6 +126,7 @@ start numbering at 1 or some other integer, provide ``count_from=1``. """ + from __future__ import annotations from typing import Any diff --git a/lib/sqlalchemy/ext/serializer.py b/lib/sqlalchemy/ext/serializer.py index 2fb022c349..92aae7aa7c 100644 --- a/lib/sqlalchemy/ext/serializer.py +++ b/lib/sqlalchemy/ext/serializer.py @@ -82,7 +82,6 @@ from ..orm.session import Session from ..util import b64decode from ..util import b64encode - __all__ = ["Serializer", "Deserializer", "dumps", "loads"] diff --git a/lib/sqlalchemy/future/__init__.py b/lib/sqlalchemy/future/__init__.py index 3a06418649..dfe828f666 100644 --- a/lib/sqlalchemy/future/__init__.py +++ b/lib/sqlalchemy/future/__init__.py @@ -10,6 +10,7 @@ this module is legacy as 2.0 APIs are now standard. """ + from .engine import Connection as Connection from .engine import create_engine as create_engine from .engine import Engine as Engine diff --git a/lib/sqlalchemy/inspection.py b/lib/sqlalchemy/inspection.py index c6380c7ca8..21898c1f2e 100644 --- a/lib/sqlalchemy/inspection.py +++ b/lib/sqlalchemy/inspection.py @@ -28,6 +28,7 @@ tools which build on top of SQLAlchemy configurations to be constructed in a forwards-compatible way. """ + from __future__ import annotations from typing import Any diff --git a/lib/sqlalchemy/log.py b/lib/sqlalchemy/log.py index a1ede98310..875a99c584 100644 --- a/lib/sqlalchemy/log.py +++ b/lib/sqlalchemy/log.py @@ -17,6 +17,7 @@ and :class:`_pool.Pool` objects, corresponds to a logger specific to that instance only. """ + from __future__ import annotations import logging @@ -33,7 +34,6 @@ from .util import py311 from .util import py38 from .util.typing import Literal - if py38: STACKLEVEL = True # needed as of py3.11.0b1 diff --git a/lib/sqlalchemy/orm/collections.py b/lib/sqlalchemy/orm/collections.py index 742ebfb052..01e6e6370f 100644 --- a/lib/sqlalchemy/orm/collections.py +++ b/lib/sqlalchemy/orm/collections.py @@ -105,6 +105,7 @@ The owning object and :class:`.CollectionAttributeImpl` are also reachable through the adapter, allowing for some very sophisticated behavior. """ + from __future__ import annotations import operator diff --git a/lib/sqlalchemy/orm/context.py b/lib/sqlalchemy/orm/context.py index 9acc59314a..43e3bb4657 100644 --- a/lib/sqlalchemy/orm/context.py +++ b/lib/sqlalchemy/orm/context.py @@ -2565,7 +2565,7 @@ def _determine_last_joined_entity( if not setup_joins: return None - (target, onclause, from_, flags) = setup_joins[-1] + target, onclause, from_, flags = setup_joins[-1] if isinstance( target, diff --git a/lib/sqlalchemy/orm/dependency.py b/lib/sqlalchemy/orm/dependency.py index 0019bcd68e..f861364432 100644 --- a/lib/sqlalchemy/orm/dependency.py +++ b/lib/sqlalchemy/orm/dependency.py @@ -190,7 +190,7 @@ class DependencyProcessor: if child_state not in uow.states: child_action = (None, None) else: - (deleted, listonly) = uow.states[child_state] + deleted, listonly = uow.states[child_state] if deleted: child_action = ( unitofwork.DeleteState(uow, child_state), diff --git a/lib/sqlalchemy/orm/descriptor_props.py b/lib/sqlalchemy/orm/descriptor_props.py index a493373e60..460c4d9340 100644 --- a/lib/sqlalchemy/orm/descriptor_props.py +++ b/lib/sqlalchemy/orm/descriptor_props.py @@ -10,6 +10,7 @@ that exist as configurational elements, but don't participate as actively in the load/persist ORM loop. """ + from __future__ import annotations from dataclasses import is_dataclass @@ -57,7 +58,6 @@ from ..util.typing import get_args from ..util.typing import is_fwd_ref from ..util.typing import is_pep593 - if typing.TYPE_CHECKING: from ._typing import _InstanceDict from ._typing import _RegistryType diff --git a/lib/sqlalchemy/orm/dynamic.py b/lib/sqlalchemy/orm/dynamic.py index c13d1a25f0..2dc6b82be8 100644 --- a/lib/sqlalchemy/orm/dynamic.py +++ b/lib/sqlalchemy/orm/dynamic.py @@ -45,7 +45,6 @@ from .writeonly import WriteOnlyLoader from .. import util from ..engine import result - if TYPE_CHECKING: from . import QueryableAttribute from .mapper import Mapper diff --git a/lib/sqlalchemy/orm/evaluator.py b/lib/sqlalchemy/orm/evaluator.py index 392d726e99..9d4652f113 100644 --- a/lib/sqlalchemy/orm/evaluator.py +++ b/lib/sqlalchemy/orm/evaluator.py @@ -16,7 +16,6 @@ This module is **private, for internal use by SQLAlchemy**. """ - from __future__ import annotations from typing import Type diff --git a/lib/sqlalchemy/orm/events.py b/lib/sqlalchemy/orm/events.py index 2affb00028..ea4f16422e 100644 --- a/lib/sqlalchemy/orm/events.py +++ b/lib/sqlalchemy/orm/events.py @@ -6,6 +6,7 @@ # the MIT License: https://www.opensource.org/licenses/mit-license.php """ORM event interfaces.""" + from __future__ import annotations from typing import Any diff --git a/lib/sqlalchemy/orm/instrumentation.py b/lib/sqlalchemy/orm/instrumentation.py index 7091d369b6..59c1453926 100644 --- a/lib/sqlalchemy/orm/instrumentation.py +++ b/lib/sqlalchemy/orm/instrumentation.py @@ -30,7 +30,6 @@ alternate instrumentation forms. """ - from __future__ import annotations from typing import Any diff --git a/lib/sqlalchemy/orm/loading.py b/lib/sqlalchemy/orm/loading.py index fb7efa76e0..cfd1849785 100644 --- a/lib/sqlalchemy/orm/loading.py +++ b/lib/sqlalchemy/orm/loading.py @@ -109,7 +109,7 @@ def instances(cursor: CursorResult[Any], context: QueryContext) -> Result[Any]: ) try: - (process, labels, extra) = list( + process, labels, extra = list( zip( *[ query_entity.row_processor(context, cursor) @@ -561,7 +561,7 @@ def load_on_pk_identity( if primary_key_identity is not None: mapper = query._propagate_attrs["plugin_subject"] - (_get_clause, _get_params) = mapper._get_clause + _get_clause, _get_params = mapper._get_clause # None present in ident - turn those comparisons # into "IS NULL" diff --git a/lib/sqlalchemy/orm/mapper.py b/lib/sqlalchemy/orm/mapper.py index 8ee0ac4fff..a7c361a7e9 100644 --- a/lib/sqlalchemy/orm/mapper.py +++ b/lib/sqlalchemy/orm/mapper.py @@ -15,6 +15,7 @@ This is a semi-private module; the main configurational API of the ORM is available in :class:`~sqlalchemy.orm.`. """ + from __future__ import annotations from collections import deque diff --git a/lib/sqlalchemy/orm/persistence.py b/lib/sqlalchemy/orm/persistence.py index 0b7a218ca8..2680650831 100644 --- a/lib/sqlalchemy/orm/persistence.py +++ b/lib/sqlalchemy/orm/persistence.py @@ -15,6 +15,7 @@ The functions here are called only by the unit of work functions in unitofwork.py. """ + from __future__ import annotations from itertools import chain diff --git a/lib/sqlalchemy/orm/properties.py b/lib/sqlalchemy/orm/properties.py index 65d3fcc3f1..118b5158f0 100644 --- a/lib/sqlalchemy/orm/properties.py +++ b/lib/sqlalchemy/orm/properties.py @@ -912,10 +912,9 @@ class MappedColumn( ) else: detail = ( - f"""none of { - ", ".join(f"'{t}'" for t in checks) - } """ - "are resolvable by the registry" + "none of " + + ", ".join(f"'{t}'" for t in checks) + + " are resolvable by the registry" ) raise orm_exc.MappedAnnotationError( "Could not locate SQLAlchemy Core type when resolving " diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py index 3c58430050..696b04276f 100644 --- a/lib/sqlalchemy/orm/query.py +++ b/lib/sqlalchemy/orm/query.py @@ -18,6 +18,7 @@ ORM session, whereas the ``Select`` construct interacts directly with the database to return iterable result sets. """ + from __future__ import annotations import collections.abc as collections_abc @@ -95,7 +96,6 @@ from ..util.typing import Literal from ..util.typing import Self from ..util.typing import SupportsIndex - if TYPE_CHECKING: from ._typing import _EntityType from ._typing import _ExternalEntityType diff --git a/lib/sqlalchemy/orm/relationships.py b/lib/sqlalchemy/orm/relationships.py index 723a51ea2f..df0365f8e7 100644 --- a/lib/sqlalchemy/orm/relationships.py +++ b/lib/sqlalchemy/orm/relationships.py @@ -13,6 +13,7 @@ SQL annotation and aliasing behavior focused on the `primaryjoin` and `secondaryjoin` aspects of :func:`_orm.relationship`. """ + from __future__ import annotations import collections diff --git a/lib/sqlalchemy/orm/session.py b/lib/sqlalchemy/orm/session.py index 72abbb46e4..623ab00a02 100644 --- a/lib/sqlalchemy/orm/session.py +++ b/lib/sqlalchemy/orm/session.py @@ -4810,7 +4810,7 @@ class Session(_SessionClassMethods, EventTarget): ) or not hasattr(attr.impl, "get_history"): continue - (added, unchanged, deleted) = attr.impl.get_history( + added, unchanged, deleted = attr.impl.get_history( state, dict_, passive=PassiveFlag.NO_CHANGE ) diff --git a/lib/sqlalchemy/orm/unitofwork.py b/lib/sqlalchemy/orm/unitofwork.py index c65b37e54c..7de3b88316 100644 --- a/lib/sqlalchemy/orm/unitofwork.py +++ b/lib/sqlalchemy/orm/unitofwork.py @@ -30,7 +30,6 @@ from .. import event from .. import util from ..util import topological - if TYPE_CHECKING: from .dependency import DependencyProcessor from .interfaces import MapperProperty @@ -521,7 +520,7 @@ class Preprocess(IterateMappersMixin): for mapper in self._mappers(uow): for state in uow.mappers[mapper].difference(self.processed): - (isdelete, listonly) = uow.states[state] + isdelete, listonly = uow.states[state] if not listonly: if isdelete: delete_states.add(state) @@ -607,7 +606,7 @@ class ProcessAll(IterateMappersMixin, PostSortRec): def _elements(self, uow): for mapper in self._mappers(uow): for state in uow.mappers[mapper]: - (isdelete, listonly) = uow.states[state] + isdelete, listonly = uow.states[state] if isdelete == self.isdelete and not listonly: yield state diff --git a/lib/sqlalchemy/pool/impl.py b/lib/sqlalchemy/pool/impl.py index f3a5c2dd84..758e7fdf5e 100644 --- a/lib/sqlalchemy/pool/impl.py +++ b/lib/sqlalchemy/pool/impl.py @@ -7,6 +7,7 @@ """Pool implementation classes.""" + from __future__ import annotations import threading diff --git a/lib/sqlalchemy/sql/_orm_types.py b/lib/sqlalchemy/sql/_orm_types.py index 39754a3c2d..ead3a770c0 100644 --- a/lib/sqlalchemy/sql/_orm_types.py +++ b/lib/sqlalchemy/sql/_orm_types.py @@ -11,7 +11,6 @@ are meaningful to the ORM. """ - from __future__ import annotations from ..util.typing import Literal diff --git a/lib/sqlalchemy/sql/_py_util.py b/lib/sqlalchemy/sql/_py_util.py index c65e96c0db..b5608efc14 100644 --- a/lib/sqlalchemy/sql/_py_util.py +++ b/lib/sqlalchemy/sql/_py_util.py @@ -32,7 +32,7 @@ class prefix_anon_map(Dict[str, str]): """ def __missing__(self, key: str) -> str: - (ident, derived) = key.split(" ", 1) + ident, derived = key.split(" ", 1) anonymous_counter = self.get(derived, 1) self[derived] = anonymous_counter + 1 # type: ignore value = f"{derived}_{anonymous_counter}" diff --git a/lib/sqlalchemy/sql/base.py b/lib/sqlalchemy/sql/base.py index 39772c9e76..b5e6cbc148 100644 --- a/lib/sqlalchemy/sql/base.py +++ b/lib/sqlalchemy/sql/base.py @@ -8,7 +8,6 @@ """Foundational utilities common to many sql modules.""" - from __future__ import annotations import collections diff --git a/lib/sqlalchemy/sql/compiler.py b/lib/sqlalchemy/sql/compiler.py index 5efc232673..02b40029de 100644 --- a/lib/sqlalchemy/sql/compiler.py +++ b/lib/sqlalchemy/sql/compiler.py @@ -23,6 +23,7 @@ To generate user-defined SQL strings, see :doc:`/ext/compiler`. """ + from __future__ import annotations import collections @@ -2129,7 +2130,7 @@ class SQLCompiler(Compiled): leep_res = self._literal_execute_expanding_parameter( escaped_name, parameter, values ) - (to_update, replacement_expr) = leep_res + to_update, replacement_expr = leep_res to_update_sets[escaped_name] = to_update replacement_expressions[escaped_name] = replacement_expr diff --git a/lib/sqlalchemy/sql/crud.py b/lib/sqlalchemy/sql/crud.py index d37274c8e0..80e90eb838 100644 --- a/lib/sqlalchemy/sql/crud.py +++ b/lib/sqlalchemy/sql/crud.py @@ -10,6 +10,7 @@ within INSERT and UPDATE statements. """ + from __future__ import annotations import functools @@ -848,7 +849,7 @@ def _setup_delete_return_defaults( toplevel, kw, ): - (_, _, implicit_return_defaults, *_) = _get_returning_modifiers( + _, _, implicit_return_defaults, *_ = _get_returning_modifiers( compiler, stmt, compile_state, toplevel ) diff --git a/lib/sqlalchemy/sql/ddl.py b/lib/sqlalchemy/sql/ddl.py index 636500ee8c..eda87c221b 100644 --- a/lib/sqlalchemy/sql/ddl.py +++ b/lib/sqlalchemy/sql/ddl.py @@ -11,6 +11,7 @@ Provides the hierarchy of DDL-defining schema items as well as routines to invoke them for a create/drop call. """ + from __future__ import annotations import contextlib diff --git a/lib/sqlalchemy/sql/dml.py b/lib/sqlalchemy/sql/dml.py index ac769648ab..ad4f0f57d3 100644 --- a/lib/sqlalchemy/sql/dml.py +++ b/lib/sqlalchemy/sql/dml.py @@ -9,6 +9,7 @@ Provide :class:`_expression.Insert`, :class:`_expression.Update` and :class:`_expression.Delete`. """ + from __future__ import annotations import collections.abc as collections_abc diff --git a/lib/sqlalchemy/sql/elements.py b/lib/sqlalchemy/sql/elements.py index dcecb20c4e..6a9df12412 100644 --- a/lib/sqlalchemy/sql/elements.py +++ b/lib/sqlalchemy/sql/elements.py @@ -80,7 +80,6 @@ from ..util.typing import Literal from ..util.typing import ParamSpec from ..util.typing import Self - if typing.TYPE_CHECKING: from ._typing import _ByArgument from ._typing import _ColumnExpressionArgument diff --git a/lib/sqlalchemy/sql/expression.py b/lib/sqlalchemy/sql/expression.py index b4a185a09c..b91376c440 100644 --- a/lib/sqlalchemy/sql/expression.py +++ b/lib/sqlalchemy/sql/expression.py @@ -7,7 +7,6 @@ """Defines the public namespace for SQL expression constructs.""" - from __future__ import annotations from ._dml_constructors import delete as delete diff --git a/lib/sqlalchemy/sql/lambdas.py b/lib/sqlalchemy/sql/lambdas.py index a9e94aec13..4d53240c51 100644 --- a/lib/sqlalchemy/sql/lambdas.py +++ b/lib/sqlalchemy/sql/lambdas.py @@ -44,7 +44,6 @@ from .. import inspection from .. import util from ..util.typing import Literal - if TYPE_CHECKING: from .elements import BindParameter from .elements import ClauseElement @@ -301,7 +300,7 @@ class LambdaElement(elements.ClauseElement): rec = lambda_element._rec if rec.bindparam_trackers: tracker_instrumented_fn = ( - rec.tracker_instrumented_fn # type:ignore [union-attr] # noqa: E501 + rec.tracker_instrumented_fn # type: ignore [union-attr] # noqa: E501 ) for tracker in rec.bindparam_trackers: tracker( diff --git a/lib/sqlalchemy/sql/schema.py b/lib/sqlalchemy/sql/schema.py index 7de91565f6..b893bf7245 100644 --- a/lib/sqlalchemy/sql/schema.py +++ b/lib/sqlalchemy/sql/schema.py @@ -28,6 +28,7 @@ Since these objects are part of the SQL expression language, they are usable as components in SQL expressions. """ + from __future__ import annotations from abc import ABC @@ -2357,11 +2358,9 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]): if existing_col is not self: if not allow_replacements: raise exc.DuplicateColumnError( - f"A column with {conflicts_on} " - f"""'{ + f"A column with {conflicts_on} " f"""'{ self.key if conflicts_on == 'key' else self.name - }' """ - f"is already present in table '{table.name}'." + }' """ f"is already present in table '{table.name}'." ) for fk in existing_col.foreign_keys: table.foreign_keys.remove(fk) diff --git a/lib/sqlalchemy/sql/selectable.py b/lib/sqlalchemy/sql/selectable.py index d7fd2cc9d2..4a2a318dc1 100644 --- a/lib/sqlalchemy/sql/selectable.py +++ b/lib/sqlalchemy/sql/selectable.py @@ -103,7 +103,6 @@ from ..util.typing import Literal from ..util.typing import Protocol from ..util.typing import Self - and_ = BooleanClauseList.and_ @@ -5063,7 +5062,7 @@ class SelectState(util.MemoizedSlots, CompileState): raw_columns, left, right, onclause ) else: - (replace_from_obj_index) = self._join_place_explicit_left_side( + replace_from_obj_index = self._join_place_explicit_left_side( left ) diff --git a/lib/sqlalchemy/sql/sqltypes.py b/lib/sqlalchemy/sql/sqltypes.py index dccc64bba1..98fa8890f9 100644 --- a/lib/sqlalchemy/sql/sqltypes.py +++ b/lib/sqlalchemy/sql/sqltypes.py @@ -7,6 +7,7 @@ # mypy: allow-untyped-defs, allow-untyped-calls """SQL specific types.""" + from __future__ import annotations import collections.abc as collections_abc @@ -3637,7 +3638,6 @@ class Uuid(Emulated, TypeEngine[_UUID_RETURN]): from sqlalchemy import Uuid from sqlalchemy import Table, Column, MetaData, String - metadata_obj = MetaData() t = Table( diff --git a/lib/sqlalchemy/sql/traversals.py b/lib/sqlalchemy/sql/traversals.py index c9b6290f46..56a7c5f688 100644 --- a/lib/sqlalchemy/sql/traversals.py +++ b/lib/sqlalchemy/sql/traversals.py @@ -35,7 +35,6 @@ from .. import util from ..util import langhelpers from ..util.typing import Self - SKIP_TRAVERSE = util.symbol("skip_traverse") COMPARE_FAILED = False COMPARE_SUCCEEDED = True diff --git a/lib/sqlalchemy/sql/util.py b/lib/sqlalchemy/sql/util.py index a0a0934f4d..9f1127b01e 100644 --- a/lib/sqlalchemy/sql/util.py +++ b/lib/sqlalchemy/sql/util.py @@ -7,6 +7,7 @@ # mypy: allow-untyped-defs, allow-untyped-calls """High level utilities which build upon other modules here.""" + from __future__ import annotations from collections import deque @@ -852,7 +853,7 @@ def splice_joins( adapter = ClauseAdapter(left) ret = None while stack: - (right, prevright) = stack.pop() + right, prevright = stack.pop() if isinstance(right, Join) and right is not stop_on: right = right._clone() right.onclause = adapter.traverse(right.onclause) diff --git a/lib/sqlalchemy/testing/engines.py b/lib/sqlalchemy/testing/engines.py index 5c20ee728a..e509c94136 100644 --- a/lib/sqlalchemy/testing/engines.py +++ b/lib/sqlalchemy/testing/engines.py @@ -27,7 +27,6 @@ from .. import pool from ..util import await_only from ..util.typing import Literal - if typing.TYPE_CHECKING: from ..engine import Engine from ..engine.url import URL diff --git a/lib/sqlalchemy/testing/fixtures/mypy.py b/lib/sqlalchemy/testing/fixtures/mypy.py index 2bed5fc328..baac539afb 100644 --- a/lib/sqlalchemy/testing/fixtures/mypy.py +++ b/lib/sqlalchemy/testing/fixtures/mypy.py @@ -42,8 +42,7 @@ class MypyTest(TestBase): with open( Path(cachedir) / "sqla_mypy_config.cfg", "w" ) as config_file: - config_file.write( - f""" + config_file.write(f""" [mypy]\n plugins = sqlalchemy.ext.mypy.plugin\n show_error_codes = True\n @@ -53,13 +52,11 @@ class MypyTest(TestBase): [mypy-sqlalchemy.*] ignore_errors = True - """ - ) + """) with open( Path(cachedir) / "plain_mypy_config.cfg", "w" ) as config_file: - config_file.write( - f""" + config_file.write(f""" [mypy]\n show_error_codes = True\n {mypy_path} @@ -67,8 +64,7 @@ class MypyTest(TestBase): [mypy-sqlalchemy.*] ignore_errors = True - """ - ) + """) yield cachedir @config.fixture() diff --git a/lib/sqlalchemy/testing/plugin/bootstrap.py b/lib/sqlalchemy/testing/plugin/bootstrap.py index 3d0d06241d..5498e87c61 100644 --- a/lib/sqlalchemy/testing/plugin/bootstrap.py +++ b/lib/sqlalchemy/testing/plugin/bootstrap.py @@ -27,7 +27,6 @@ import importlib.util import os import sys - bootstrap_file = locals()["bootstrap_file"] to_bootstrap = locals()["to_bootstrap"] diff --git a/lib/sqlalchemy/testing/plugin/pytestplugin.py b/lib/sqlalchemy/testing/plugin/pytestplugin.py index bee8189edb..c430e76c10 100644 --- a/lib/sqlalchemy/testing/plugin/pytestplugin.py +++ b/lib/sqlalchemy/testing/plugin/pytestplugin.py @@ -654,13 +654,10 @@ def _pytest_fn_decorator(target): __target_fn="__target_fn", __orig_fn="__orig_fn", name=fn.__name__ ) metadata.update(format_argspec_plus(spec, grouped=False)) - code = ( - """\ + code = """\ def %(name)s%(grouped_args)s: return %(__target_fn)s(%(__orig_fn)s, %(apply_kw)s) -""" - % metadata - ) +""" % metadata decorated = _exec_code_in_env( code, {"__target_fn": target, "__orig_fn": fn}, fn.__name__ ) diff --git a/lib/sqlalchemy/testing/profiling.py b/lib/sqlalchemy/testing/profiling.py index 37ddc02337..79a45871d4 100644 --- a/lib/sqlalchemy/testing/profiling.py +++ b/lib/sqlalchemy/testing/profiling.py @@ -29,7 +29,6 @@ from .util import gc_collect from ..util import freethreading from ..util import has_compiled_ext - try: import cProfile except ImportError: diff --git a/lib/sqlalchemy/testing/provision.py b/lib/sqlalchemy/testing/provision.py index b61cb5035f..a3f72363e3 100644 --- a/lib/sqlalchemy/testing/provision.py +++ b/lib/sqlalchemy/testing/provision.py @@ -25,7 +25,6 @@ from ..sql import ddl from ..sql import schema from ..util import decorator - log = logging.getLogger(__name__) FOLLOWER_IDENT = None diff --git a/lib/sqlalchemy/testing/suite/test_reflection.py b/lib/sqlalchemy/testing/suite/test_reflection.py index 8f6fe56842..d808783eb9 100644 --- a/lib/sqlalchemy/testing/suite/test_reflection.py +++ b/lib/sqlalchemy/testing/suite/test_reflection.py @@ -52,7 +52,6 @@ from ...testing import is_none from ...testing import is_true from ...testing import mock - metadata, users = None, None diff --git a/lib/sqlalchemy/testing/util.py b/lib/sqlalchemy/testing/util.py index 05aff5f36c..8e2c6996d9 100644 --- a/lib/sqlalchemy/testing/util.py +++ b/lib/sqlalchemy/testing/util.py @@ -40,7 +40,6 @@ from ..util import defaultdict from ..util import has_refcount_gc from ..util import inspect_getfullargspec - if not has_refcount_gc: def non_refcount_gc_collect(*args): diff --git a/lib/sqlalchemy/types.py b/lib/sqlalchemy/types.py index 23b9eac403..27e3669939 100644 --- a/lib/sqlalchemy/types.py +++ b/lib/sqlalchemy/types.py @@ -7,7 +7,6 @@ """Compatibility namespace for sqlalchemy.sql.types.""" - from __future__ import annotations from .sql.sqltypes import _Binary as _Binary diff --git a/lib/sqlalchemy/util/_collections.py b/lib/sqlalchemy/util/_collections.py index f67fbf7c1e..8ac193f151 100644 --- a/lib/sqlalchemy/util/_collections.py +++ b/lib/sqlalchemy/util/_collections.py @@ -7,6 +7,7 @@ # mypy: allow-untyped-defs, allow-untyped-calls """Collection classes and helpers.""" + from __future__ import annotations import operator @@ -63,7 +64,6 @@ else: unique_list as unique_list, ) - _T = TypeVar("_T", bound=Any) _KT = TypeVar("_KT", bound=Any) _VT = TypeVar("_VT", bound=Any) diff --git a/lib/sqlalchemy/util/compat.py b/lib/sqlalchemy/util/compat.py index 9476242251..de4c9515b9 100644 --- a/lib/sqlalchemy/util/compat.py +++ b/lib/sqlalchemy/util/compat.py @@ -33,7 +33,6 @@ from typing import Tuple from typing import Type from typing import TypeVar - py314b1 = sys.version_info >= (3, 14, 0, "beta", 1) py314 = sys.version_info >= (3, 14) py313 = sys.version_info >= (3, 13) diff --git a/lib/sqlalchemy/util/langhelpers.py b/lib/sqlalchemy/util/langhelpers.py index cb72771e37..febe5dbee2 100644 --- a/lib/sqlalchemy/util/langhelpers.py +++ b/lib/sqlalchemy/util/langhelpers.py @@ -10,6 +10,7 @@ modules, classes, hierarchies, attributes, functions, and methods. """ + from __future__ import annotations import collections @@ -277,21 +278,15 @@ def decorator(target: Callable[..., Any]) -> Callable[[_Fn], _Fn]: # more kinds of methods that use @decorator, things may have to # be further improved in this area if "__" in repr(spec[0]): - code = ( - """\ + code = """\ %(prefix)sdef %(name)s%(grouped_args)s: return %(target_prefix)s%(target)s(%(fn)s, %(apply_pos)s) -""" - % metadata - ) +""" % metadata else: - code = ( - """\ + code = """\ %(prefix)sdef %(name)s%(grouped_args)s: return %(target_prefix)s%(target)s(%(fn)s, %(apply_kw)s) -""" - % metadata - ) +""" % metadata env: Dict[str, Any] = { targ_name: target, @@ -1564,9 +1559,13 @@ class hybridmethod(Generic[_T]): def __get__(self, instance: Any, owner: Any) -> Callable[..., _T]: if instance is None: - return self.clslevel.__get__(owner, owner.__class__) # type:ignore + return self.clslevel.__get__( # type: ignore[no-any-return] + owner, owner.__class__ + ) else: - return self.func.__get__(instance, owner) # type:ignore + return self.func.__get__( # type: ignore[no-any-return] + instance, owner + ) def classlevel(self, func: Callable[..., Any]) -> hybridmethod[_T]: self.clslevel = func @@ -1862,7 +1861,7 @@ def _warnings_warn( if frame.f_code in _warning_tags: warning_tag_found = True - (_suffix, _category) = _warning_tags[frame.f_code] + _suffix, _category = _warning_tags[frame.f_code] category = category or _category message = f"{message} ({_suffix})" diff --git a/lib/sqlalchemy/util/preloaded.py b/lib/sqlalchemy/util/preloaded.py index b57abdc4d5..6ef6719568 100644 --- a/lib/sqlalchemy/util/preloaded.py +++ b/lib/sqlalchemy/util/preloaded.py @@ -10,6 +10,7 @@ runtime. """ + from __future__ import annotations import sys diff --git a/lib/sqlalchemy/util/queue.py b/lib/sqlalchemy/util/queue.py index c89f9d23c6..ab4f3e3a4c 100644 --- a/lib/sqlalchemy/util/queue.py +++ b/lib/sqlalchemy/util/queue.py @@ -18,6 +18,7 @@ producing a ``put()`` inside the ``get()`` and therefore a reentrant condition. """ + from __future__ import annotations import asyncio @@ -36,7 +37,6 @@ from .concurrency import await_fallback from .concurrency import await_only from .langhelpers import memoized_property - _T = TypeVar("_T", bound=Any) __all__ = ["Empty", "Full", "Queue"] diff --git a/lib/sqlalchemy/util/tool_support.py b/lib/sqlalchemy/util/tool_support.py index 9e1246f8f0..7ad4fbf6a1 100644 --- a/lib/sqlalchemy/util/tool_support.py +++ b/lib/sqlalchemy/util/tool_support.py @@ -11,6 +11,7 @@ These aren't imported by the enclosing util package as the are not needed for normal library use. """ + from __future__ import annotations from argparse import ArgumentParser diff --git a/pyproject.toml b/pyproject.toml index 628ff4af61..0f870d6874 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -88,7 +88,7 @@ lint = [ "flake8-rst-docstrings", "pydocstyle<4.0.0", "pygments", - "black==25.11.0", + "black==26.3.1", "slotscheck>=0.17.0", "zimports>=0.7.0", # required by generate_tuple_map_overloads ] diff --git a/reap_dbs.py b/reap_dbs.py index c6d2616e6d..cb2d402bd7 100644 --- a/reap_dbs.py +++ b/reap_dbs.py @@ -16,7 +16,6 @@ import sys from sqlalchemy.testing import provision - logging.basicConfig() logging.getLogger(provision.__name__).setLevel(logging.INFO) diff --git a/test/aaa_profiling/test_compiler.py b/test/aaa_profiling/test_compiler.py index dced8dee06..e7a8482de0 100644 --- a/test/aaa_profiling/test_compiler.py +++ b/test/aaa_profiling/test_compiler.py @@ -10,7 +10,6 @@ from sqlalchemy.testing import AssertsExecutionResults from sqlalchemy.testing import fixtures from sqlalchemy.testing import profiling - t1 = t2 = None diff --git a/test/aaa_profiling/test_resultset.py b/test/aaa_profiling/test_resultset.py index 049e4a45e5..07e74450c6 100644 --- a/test/aaa_profiling/test_resultset.py +++ b/test/aaa_profiling/test_resultset.py @@ -13,7 +13,6 @@ from sqlalchemy.testing import eq_ from sqlalchemy.testing import fixtures from sqlalchemy.testing import profiling - NUM_FIELDS = 10 NUM_RECORDS = 1000 diff --git a/test/base/test_examples.py b/test/base/test_examples.py index 4baddfb105..113626553e 100644 --- a/test/base/test_examples.py +++ b/test/base/test_examples.py @@ -3,7 +3,6 @@ import sys from sqlalchemy.testing import fixtures - here = os.path.dirname(__file__) sqla_base = os.path.normpath(os.path.join(here, "..", "..")) diff --git a/test/conftest.py b/test/conftest.py index b7f2d945ca..a39f66c296 100755 --- a/test/conftest.py +++ b/test/conftest.py @@ -6,12 +6,12 @@ This script is an extension to pytest which installs SQLAlchemy's testing plugin into the local environment. """ + import os import sys import pytest - os.environ["SQLALCHEMY_WARN_20"] = "true" collect_ignore_glob = [] diff --git a/test/dialect/mssql/test_query.py b/test/dialect/mssql/test_query.py index 33f648b82a..28c0de2e75 100644 --- a/test/dialect/mssql/test_query.py +++ b/test/dialect/mssql/test_query.py @@ -443,20 +443,16 @@ class MatchTest(AssertsCompiledSQL, fixtures.TablesTest): event.listen( metadata, "after_create", - DDL( - """CREATE FULLTEXT INDEX + DDL("""CREATE FULLTEXT INDEX ON cattable (description) - KEY INDEX PK_cattable""" - ), + KEY INDEX PK_cattable"""), ) event.listen( metadata, "after_create", - DDL( - """CREATE FULLTEXT INDEX + DDL("""CREATE FULLTEXT INDEX ON matchtable (title) - KEY INDEX PK_matchtable""" - ), + KEY INDEX PK_matchtable"""), ) event.listen( @@ -614,8 +610,7 @@ class TableValuedTest(fixtures.TestBase): @testing.fixture def scalar_strings(self, connection): - connection.exec_driver_sql( - """ + connection.exec_driver_sql(""" CREATE FUNCTION scalar_strings ( ) @@ -627,15 +622,13 @@ RETURN FROM ( VALUES ('some string'), ('some string'), ('some string') ) AS my_tab(my_string) - """ - ) + """) yield connection.exec_driver_sql("DROP FUNCTION scalar_strings") @testing.fixture def two_strings(self, connection): - connection.exec_driver_sql( - """ + connection.exec_driver_sql(""" CREATE FUNCTION three_pairs ( ) RETURNS TABLE @@ -646,8 +639,7 @@ RETURN FROM ( VALUES ('a', 'b'), ('c', 'd'), ('e', 'f') ) AS my_tab(s1, s2) -""" - ) +""") yield connection.exec_driver_sql("DROP FUNCTION three_pairs") diff --git a/test/dialect/oracle/test_dialect.py b/test/dialect/oracle/test_dialect.py index 1f8a23f70d..e96d08f4ce 100644 --- a/test/dialect/oracle/test_dialect.py +++ b/test/dialect/oracle/test_dialect.py @@ -516,8 +516,7 @@ class OutParamTest(fixtures.TestBase, AssertsExecutionResults): @classmethod def setup_test_class(cls): with testing.db.begin() as c: - c.exec_driver_sql( - """ + c.exec_driver_sql(""" create or replace procedure foo(x_in IN number, x_out OUT number, y_out OUT number, z_out OUT varchar) IS retval number; @@ -527,8 +526,7 @@ begin y_out := x_in * 15; z_out := NULL; end; - """ - ) + """) def test_out_params(self, connection): result = connection.execute( @@ -1132,8 +1130,7 @@ class TableValuedTest(fixtures.TestBase): connection.exec_driver_sql( "CREATE OR REPLACE TYPE strings_t IS TABLE OF VARCHAR2 (100)" ) - connection.exec_driver_sql( - r""" + connection.exec_driver_sql(r""" CREATE OR REPLACE FUNCTION scalar_strings ( count_in IN INTEGER, string_in IN VARCHAR2) RETURN strings_t @@ -1150,31 +1147,25 @@ BEGIN RETURN l_strings; END; - """ - ) + """) yield connection.exec_driver_sql("DROP FUNCTION scalar_strings") connection.exec_driver_sql("DROP TYPE strings_t") @testing.fixture def two_strings(self, connection): - connection.exec_driver_sql( - """ + connection.exec_driver_sql(""" CREATE OR REPLACE TYPE two_strings_ot AUTHID DEFINER IS OBJECT ( string1 VARCHAR2 (10), string2 VARCHAR2 (10) -)""" - ) - connection.exec_driver_sql( - """ +)""") + connection.exec_driver_sql(""" CREATE OR REPLACE TYPE two_strings_nt IS TABLE OF two_strings_ot -""" - ) +""") - connection.exec_driver_sql( - """ + connection.exec_driver_sql(""" CREATE OR REPLACE FUNCTION three_pairs RETURN two_strings_nt AUTHID DEFINER @@ -1185,8 +1176,7 @@ BEGIN two_strings_ot ('c', 'd'), two_strings_ot ('e', 'f')); END; -""" - ) +""") yield connection.exec_driver_sql("DROP FUNCTION three_pairs") connection.exec_driver_sql("DROP TYPE two_strings_nt") diff --git a/test/dialect/oracle/test_reflection.py b/test/dialect/oracle/test_reflection.py index 456b056a09..9b6adb9166 100644 --- a/test/dialect/oracle/test_reflection.py +++ b/test/dialect/oracle/test_reflection.py @@ -64,8 +64,7 @@ class MultiSchemaTest(fixtures.TestBase, AssertsCompiledSQL): # we connect as the other user. with testing.db.begin() as conn: - for stmt in ( - """ + for stmt in (""" create table %(test_schema)s.parent( id integer primary key, data varchar2(50) @@ -97,17 +96,14 @@ class MultiSchemaTest(fixtures.TestBase, AssertsCompiledSQL): -- so we give it to public. ideas welcome. grant references on %(test_schema)s.parent to public; grant references on %(test_schema)s.child to public; - """ - % {"test_schema": testing.config.test_schema} - ).split(";"): + """ % {"test_schema": testing.config.test_schema}).split(";"): if stmt.strip(): conn.exec_driver_sql(stmt) @classmethod def teardown_test_class(cls): with testing.db.begin() as conn: - for stmt in ( - """ + for stmt in (""" drop table %(test_schema)s.child; drop table %(test_schema)s.parent; drop table local_table; @@ -116,9 +112,7 @@ class MultiSchemaTest(fixtures.TestBase, AssertsCompiledSQL): drop synonym %(test_schema)s_pt; drop synonym %(test_schema)s.local_table; - """ - % {"test_schema": testing.config.test_schema} - ).split(";"): + """ % {"test_schema": testing.config.test_schema}).split(";"): if stmt.strip(): conn.exec_driver_sql(stmt) @@ -767,9 +761,7 @@ class ViewReflectionTest(fixtures.TestBase): ) sql += """ CREATE SYNONYM syn_link FOR tbl_plain_v@%(link)s; - """ % { - "link": cls.dblink - } + """ % {"link": cls.dblink} with testing.db.begin() as conn: for stmt in ( sql % {"test_schema": testing.config.test_schema} @@ -1019,20 +1011,14 @@ class RoundTripIndexTest(fixtures.TestBase): Column("other", Unicode(255), index=True), ) metadata.create_all(connection) - connection.exec_driver_sql( - """create index idx3 on sometable( - lower("group"), other, upper(other))""" - ) - connection.exec_driver_sql( - """create index idx1 on sometable - (("group" || col), col || other desc)""" - ) - connection.exec_driver_sql( - """ + connection.exec_driver_sql("""create index idx3 on sometable( + lower("group"), other, upper(other))""") + connection.exec_driver_sql("""create index idx1 on sometable + (("group" || col), col || other desc)""") + connection.exec_driver_sql(""" create unique index idx2 on sometable (col desc, lower(other), "group" asc) - """ - ) + """) expected = [ { @@ -1157,13 +1143,11 @@ class RoundTripIndexTest(fixtures.TestBase): # find what the primary k constraint name should be primaryconsname = connection.scalar( - text( - """SELECT constraint_name + text("""SELECT constraint_name FROM all_constraints WHERE table_name = :table_name AND owner = :owner - AND constraint_type = 'P' """ - ), + AND constraint_type = 'P' """), dict( table_name=s_table.name.upper(), owner=testing.db.dialect.default_schema_name.upper(), diff --git a/test/dialect/postgresql/test_dialect.py b/test/dialect/postgresql/test_dialect.py index ce8ff27a2d..d41ef09ade 100644 --- a/test/dialect/postgresql/test_dialect.py +++ b/test/dialect/postgresql/test_dialect.py @@ -166,15 +166,12 @@ class DialectTest(fixtures.TestBase): event.listen( metadata, "after_create", - DDL( - """ + DDL(""" CREATE OR REPLACE FUNCTION %s.version() RETURNS integer AS $$ BEGIN return 0; END; -$$ LANGUAGE plpgsql;""" - % (default_schema_name,) - ), +$$ LANGUAGE plpgsql;""" % (default_schema_name,)), ) event.listen( metadata, @@ -1276,16 +1273,14 @@ class MiscBackendTest( conn = testing.db.connect() trans = conn.begin() try: - conn.exec_driver_sql( - """ + conn.exec_driver_sql(""" CREATE OR REPLACE FUNCTION note(message varchar) RETURNS integer AS $$ BEGIN RAISE NOTICE 'notice: %%', message; RETURN NULL; END; $$ LANGUAGE plpgsql; -""" - ) +""") conn.exec_driver_sql("SELECT note('hi there')") conn.exec_driver_sql("SELECT note('another note')") finally: @@ -1460,18 +1455,14 @@ $$ LANGUAGE plpgsql; execute that DefaultClause upon insert.""" meta = self.metadata - connection.execute( - text( - """ + connection.execute(text(""" CREATE TABLE speedy_users ( speedy_user_id SERIAL PRIMARY KEY, user_name VARCHAR NOT NULL, user_password VARCHAR NOT NULL ); - """ - ) - ) + """)) t = Table("speedy_users", meta, autoload_with=connection) r = connection.execute( t.insert(), dict(user_name="user", user_password="lala") diff --git a/test/dialect/postgresql/test_reflection.py b/test/dialect/postgresql/test_reflection.py index df7247dd7a..5120d97a34 100644 --- a/test/dialect/postgresql/test_reflection.py +++ b/test/dialect/postgresql/test_reflection.py @@ -1718,34 +1718,28 @@ class ReflectionTest( Column("other", String(20)), ) metadata.create_all(connection) - connection.exec_driver_sql( - """ + connection.exec_driver_sql(""" create index idx3 on party (lower(name::text), other, lower(aname::text) desc) - """ - ) + """) connection.exec_driver_sql( "create index idx1 on party ((id || name), (other || id::text))" ) connection.exec_driver_sql( "create unique index idx2 on party (id) where name = 'test'" ) - connection.exec_driver_sql( - """ + connection.exec_driver_sql(""" create index idx4 on party using btree (name nulls first, lower(other), aname desc) where name != 'foo' - """ - ) + """) version = connection.dialect.server_version_info if version >= (15,): - connection.exec_driver_sql( - """ + connection.exec_driver_sql(""" create unique index zz_idx5 on party (name desc, upper(other)) nulls not distinct - """ - ) + """) expected = [ { @@ -1889,28 +1883,22 @@ class ReflectionTest( t1.create(connection) # check ASC, DESC options alone - connection.exec_driver_sql( - """ + connection.exec_driver_sql(""" create index idx1 on party (id, name ASC, aname DESC) - """ - ) + """) # check DESC w/ NULLS options - connection.exec_driver_sql( - """ + connection.exec_driver_sql(""" create index idx2 on party (name DESC NULLS FIRST, aname DESC NULLS LAST) - """ - ) + """) # check ASC w/ NULLS options - connection.exec_driver_sql( - """ + connection.exec_driver_sql(""" create index idx3 on party (name ASC NULLS FIRST, aname ASC NULLS LAST) - """ - ) + """) # reflect data m2 = MetaData() @@ -2175,19 +2163,15 @@ class ReflectionTest( ) metadata.create_all(connection) connection.exec_driver_sql("CREATE INDEX idx1 ON t (x) INCLUDE (name)") - connection.exec_driver_sql( - """ + connection.exec_driver_sql(""" create index idx3 on t (lower(name::text), other desc nulls last, lower(aname::text)) include (id, x) - """ - ) - connection.exec_driver_sql( - """ + """) + connection.exec_driver_sql(""" create unique index idx2 on t using btree (lower(other), (id * id)) include (id) - """ - ) + """) ind = connection.dialect.get_indexes(connection, "t", None) eq_( diff --git a/test/engine/test_parseconnect.py b/test/engine/test_parseconnect.py index 7c562bf39d..f41850f90f 100644 --- a/test/engine/test_parseconnect.py +++ b/test/engine/test_parseconnect.py @@ -29,7 +29,6 @@ from sqlalchemy.testing import mock from sqlalchemy.testing import ne_ from sqlalchemy.testing.assertions import expect_raises_message - dialect = None diff --git a/test/engine/test_pool.py b/test/engine/test_pool.py index b034e3be78..ed39465c9e 100644 --- a/test/engine/test_pool.py +++ b/test/engine/test_pool.py @@ -480,10 +480,8 @@ class PoolEventsTest(PoolTestBase): @event.listens_for(p, "reset") def reset(conn, rec, state): canary.append( - f"""reset_{ - 'rollback_ok' - if state.asyncio_safe else 'no_rollback' - }""" + "reset_" + f"{'rollback_ok' if state.asyncio_safe else 'no_rollback'}" ) @event.listens_for(p, "checkin") diff --git a/test/engine/test_reflection.py b/test/engine/test_reflection.py index 65857eaec4..3e70425327 100644 --- a/test/engine/test_reflection.py +++ b/test/engine/test_reflection.py @@ -1068,8 +1068,7 @@ class ReflectionTest(fixtures.TestBase, ComparesTables): indexes""" conn = connection - conn.exec_driver_sql( - """ + conn.exec_driver_sql(""" CREATE TABLE book ( id INTEGER NOT NULL, title VARCHAR(100) NOT NULL, @@ -1077,8 +1076,7 @@ class ReflectionTest(fixtures.TestBase, ComparesTables): series_id INTEGER, UNIQUE(series, series_id), PRIMARY KEY(id) - )""" - ) + )""") book = Table("book", metadata, autoload_with=connection) assert book.primary_key.contains_column(book.c.id) @@ -1107,8 +1105,7 @@ class ReflectionTest(fixtures.TestBase, ComparesTables): """test reflection of a composite primary key""" conn = connection - conn.exec_driver_sql( - """ + conn.exec_driver_sql(""" CREATE TABLE book ( id INTEGER NOT NULL, isbn VARCHAR(50) NOT NULL, @@ -1117,8 +1114,7 @@ class ReflectionTest(fixtures.TestBase, ComparesTables): series_id INTEGER NOT NULL, UNIQUE(series, series_id), PRIMARY KEY(id, isbn) - )""" - ) + )""") book = Table("book", metadata, autoload_with=connection) assert book.primary_key.contains_column(book.c.id) assert book.primary_key.contains_column(book.c.isbn) @@ -2042,15 +2038,13 @@ class ReverseCasingReflectTest(fixtures.TestBase, AssertsCompiledSQL): @testing.requires.denormalized_names def setup_test(self): with testing.db.begin() as conn: - conn.exec_driver_sql( - """ + conn.exec_driver_sql(""" CREATE TABLE weird_casing( col1 char(20), "Col2" char(20), "col3" char(20) ) - """ - ) + """) @testing.requires.denormalized_names def teardown_test(self): diff --git a/test/ext/mypy/plugin_files/abstract_one.py b/test/ext/mypy/plugin_files/abstract_one.py index d11631d75b..91e29f2762 100644 --- a/test/ext/mypy/plugin_files/abstract_one.py +++ b/test/ext/mypy/plugin_files/abstract_one.py @@ -3,7 +3,6 @@ from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.orm import declarative_base - Base = declarative_base() diff --git a/test/ext/mypy/plugin_files/cols_noninferred_plain_nonopt.py b/test/ext/mypy/plugin_files/cols_noninferred_plain_nonopt.py index a2825e0037..560a629735 100644 --- a/test/ext/mypy/plugin_files/cols_noninferred_plain_nonopt.py +++ b/test/ext/mypy/plugin_files/cols_noninferred_plain_nonopt.py @@ -3,7 +3,6 @@ from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.orm import registry - reg: registry = registry() diff --git a/test/ext/mypy/plugin_files/decl_attrs_one.py b/test/ext/mypy/plugin_files/decl_attrs_one.py index 1f2261cfcc..ac9e708ee7 100644 --- a/test/ext/mypy/plugin_files/decl_attrs_one.py +++ b/test/ext/mypy/plugin_files/decl_attrs_one.py @@ -6,7 +6,6 @@ from sqlalchemy.sql.schema import ForeignKey from sqlalchemy.sql.schema import MetaData from sqlalchemy.sql.schema import Table - reg: registry = registry() diff --git a/test/ext/mypy/plugin_files/decl_attrs_two.py b/test/ext/mypy/plugin_files/decl_attrs_two.py index a20af490dc..2c266cf4f4 100644 --- a/test/ext/mypy/plugin_files/decl_attrs_two.py +++ b/test/ext/mypy/plugin_files/decl_attrs_two.py @@ -7,7 +7,6 @@ from sqlalchemy.sql.schema import ForeignKey from sqlalchemy.sql.schema import MetaData from sqlalchemy.sql.schema import Table - Base = declarative_base() diff --git a/test/ext/mypy/plugin_files/imperative_table.py b/test/ext/mypy/plugin_files/imperative_table.py index 0548a79268..5ecb960ae7 100644 --- a/test/ext/mypy/plugin_files/imperative_table.py +++ b/test/ext/mypy/plugin_files/imperative_table.py @@ -9,7 +9,6 @@ from sqlalchemy import Table from sqlalchemy.orm import declarative_base from sqlalchemy.orm import Mapped - Base = declarative_base() diff --git a/test/ext/mypy/plugin_files/issue_7321.py b/test/ext/mypy/plugin_files/issue_7321.py index d4cd7f2c43..cd26a809da 100644 --- a/test/ext/mypy/plugin_files/issue_7321.py +++ b/test/ext/mypy/plugin_files/issue_7321.py @@ -4,7 +4,6 @@ from typing import Dict from sqlalchemy.orm import declarative_base from sqlalchemy.orm import declared_attr - Base = declarative_base() diff --git a/test/ext/mypy/plugin_files/issue_7321_part2.py b/test/ext/mypy/plugin_files/issue_7321_part2.py index 4227f2797e..720a6214ec 100644 --- a/test/ext/mypy/plugin_files/issue_7321_part2.py +++ b/test/ext/mypy/plugin_files/issue_7321_part2.py @@ -5,7 +5,6 @@ from typing import Type from sqlalchemy.orm import declarative_base from sqlalchemy.orm import declared_attr - Base = declarative_base() diff --git a/test/ext/mypy/plugin_files/mixin_not_mapped.py b/test/ext/mypy/plugin_files/mixin_not_mapped.py index 9a4865eb6d..e82b4d9145 100644 --- a/test/ext/mypy/plugin_files/mixin_not_mapped.py +++ b/test/ext/mypy/plugin_files/mixin_not_mapped.py @@ -4,7 +4,6 @@ from sqlalchemy import String from sqlalchemy.orm import declarative_base from sqlalchemy.orm import registry - reg: registry = registry() Base = declarative_base() diff --git a/test/ext/mypy/plugin_files/mixin_one.py b/test/ext/mypy/plugin_files/mixin_one.py index a471edf6c7..b5797ba81a 100644 --- a/test/ext/mypy/plugin_files/mixin_one.py +++ b/test/ext/mypy/plugin_files/mixin_one.py @@ -4,7 +4,6 @@ from sqlalchemy import String from sqlalchemy.orm import declarative_base from sqlalchemy.orm import registry - reg: registry = registry() # TODO: also reg.as_declarative_base() diff --git a/test/ext/mypy/plugin_files/mixin_two.py b/test/ext/mypy/plugin_files/mixin_two.py index 900b28fa49..fe705349a1 100644 --- a/test/ext/mypy/plugin_files/mixin_two.py +++ b/test/ext/mypy/plugin_files/mixin_two.py @@ -12,7 +12,6 @@ from sqlalchemy.orm.decl_api import declared_attr from sqlalchemy.orm.interfaces import MapperProperty from sqlalchemy.sql.schema import ForeignKey - reg: registry = registry() diff --git a/test/ext/mypy/plugin_files/mixin_w_tablename.py b/test/ext/mypy/plugin_files/mixin_w_tablename.py index cfbe83d35d..86e59800a4 100644 --- a/test/ext/mypy/plugin_files/mixin_w_tablename.py +++ b/test/ext/mypy/plugin_files/mixin_w_tablename.py @@ -5,7 +5,6 @@ from sqlalchemy.orm import declarative_base from sqlalchemy.orm import declared_attr from sqlalchemy.orm import Mapped - Base = declarative_base() diff --git a/test/ext/mypy/plugin_files/sa_module_prefix.py b/test/ext/mypy/plugin_files/sa_module_prefix.py index a37ae6b06f..1b05bd0045 100644 --- a/test/ext/mypy/plugin_files/sa_module_prefix.py +++ b/test/ext/mypy/plugin_files/sa_module_prefix.py @@ -4,7 +4,6 @@ from typing import Optional import sqlalchemy as sa from sqlalchemy import orm as saorm - Base = saorm.declarative_base() diff --git a/test/ext/mypy/plugin_files/typing_err3.py b/test/ext/mypy/plugin_files/typing_err3.py index 146b96b2a7..c74d899019 100644 --- a/test/ext/mypy/plugin_files/typing_err3.py +++ b/test/ext/mypy/plugin_files/typing_err3.py @@ -14,7 +14,6 @@ from sqlalchemy.orm import Mapped from sqlalchemy.orm import relationship from sqlalchemy.orm.decl_api import declared_attr - Base = declarative_base() diff --git a/test/ext/test_extendedattr.py b/test/ext/test_extendedattr.py index 47756c9495..d107be31b9 100644 --- a/test/ext/test_extendedattr.py +++ b/test/ext/test_extendedattr.py @@ -404,7 +404,7 @@ class UserDefinedExtensionTest(_ExtBase, fixtures.ORMTest): useobject=True, ) b = Blog() - (p1, p2, p3) = (Post(), Post(), Post()) + p1, p2, p3 = (Post(), Post(), Post()) b.posts.append(p1) b.posts.append(p2) b.posts.append(p3) diff --git a/test/ext/test_orderinglist.py b/test/ext/test_orderinglist.py index d3fd2a9a04..b12f9bc6f5 100644 --- a/test/ext/test_orderinglist.py +++ b/test/ext/test_orderinglist.py @@ -13,7 +13,6 @@ from sqlalchemy.testing.schema import Column from sqlalchemy.testing.schema import Table from sqlalchemy.testing.util import picklers - metadata = None diff --git a/test/orm/_fixtures.py b/test/orm/_fixtures.py index 783bfa14ab..c3fd6b8107 100644 --- a/test/orm/_fixtures.py +++ b/test/orm/_fixtures.py @@ -9,7 +9,6 @@ from sqlalchemy.testing import fixtures from sqlalchemy.testing.schema import Column from sqlalchemy.testing.schema import Table - __all__ = () diff --git a/test/orm/declarative/test_basic.py b/test/orm/declarative/test_basic.py index 1f31544e06..607609729c 100644 --- a/test/orm/declarative/test_basic.py +++ b/test/orm/declarative/test_basic.py @@ -65,7 +65,6 @@ from sqlalchemy.testing.fixtures import fixture_session from sqlalchemy.testing.schema import Column from sqlalchemy.testing.schema import Table - Base = None User = Address = None diff --git a/test/orm/declarative/test_tm_future_annotations.py b/test/orm/declarative/test_tm_future_annotations.py index 462aec8976..0e7e531ff0 100644 --- a/test/orm/declarative/test_tm_future_annotations.py +++ b/test/orm/declarative/test_tm_future_annotations.py @@ -41,7 +41,6 @@ from .test_typed_mapping import expect_annotation_syntax_error from .test_typed_mapping import MappedColumnTest as _MappedColumnTest from .test_typed_mapping import RelationshipLHSTest as _RelationshipLHSTest - _R = TypeVar("_R") M = Mapped diff --git a/test/orm/declarative/test_tm_future_annotations_sync.py b/test/orm/declarative/test_tm_future_annotations_sync.py index 0c4647d818..c5eb66b406 100644 --- a/test/orm/declarative/test_tm_future_annotations_sync.py +++ b/test/orm/declarative/test_tm_future_annotations_sync.py @@ -104,7 +104,6 @@ from sqlalchemy.testing.fixtures import fixture_session from sqlalchemy.util import compat from sqlalchemy.util.typing import Annotated - # try to differentiate between typing_extensions.TypeAliasType # and typing.TypeAliasType TypingTypeAliasType = getattr(typing, "TypeAliasType", TypeAliasType) diff --git a/test/orm/declarative/test_typed_mapping.py b/test/orm/declarative/test_typed_mapping.py index dbd208ca79..42c11fd0fa 100644 --- a/test/orm/declarative/test_typed_mapping.py +++ b/test/orm/declarative/test_typed_mapping.py @@ -95,7 +95,6 @@ from sqlalchemy.testing.fixtures import fixture_session from sqlalchemy.util import compat from sqlalchemy.util.typing import Annotated - # try to differentiate between typing_extensions.TypeAliasType # and typing.TypeAliasType TypingTypeAliasType = getattr(typing, "TypeAliasType", TypeAliasType) diff --git a/test/orm/test_attributes.py b/test/orm/test_attributes.py index b1830cdc51..0b52bbe5ef 100644 --- a/test/orm/test_attributes.py +++ b/test/orm/test_attributes.py @@ -1177,7 +1177,7 @@ class BackrefTest(fixtures.ORMTest): s.courses.remove(c) self.assert_(c.students == []) - (s1, s2, s3) = (Student(), Student(), Student()) + s1, s2, s3 = (Student(), Student(), Student()) c.students = [s1, s2, s3] self.assert_(s2.courses == [c]) @@ -1211,7 +1211,7 @@ class BackrefTest(fixtures.ORMTest): useobject=True, ) b = Blog() - (p1, p2, p3) = (Post(), Post(), Post()) + p1, p2, p3 = (Post(), Post(), Post()) b.posts.append(p1) b.posts.append(p2) b.posts.append(p3) diff --git a/test/orm/test_froms.py b/test/orm/test_froms.py index e0d75db7e1..e20ae0e3a7 100644 --- a/test/orm/test_froms.py +++ b/test/orm/test_froms.py @@ -2420,7 +2420,7 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): test_session = fixture_session() - (user7, user8, user9, user10) = test_session.query(User).all() + user7, user8, user9, user10 = test_session.query(User).all() ( address1, address2, @@ -2498,8 +2498,8 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): sess = fixture_session() - (user7, user8, user9, user10) = sess.query(User).all() - (address1, address2, address3, address4, address5) = sess.query( + user7, user8, user9, user10 = sess.query(User).all() + address1, address2, address3, address4, address5 = sess.query( Address ).all() @@ -2585,7 +2585,7 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): sess = fixture_session() - (user7, user8, user9, user10) = sess.query(User).all() + user7, user8, user9, user10 = sess.query(User).all() expected = [(user7, 1), (user8, 3), (user9, 1), (user10, 0)] q = sess.query(User) @@ -2643,7 +2643,7 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): ) sess = fixture_session() - (user7, user8, user9, user10) = sess.query(User).all() + user7, user8, user9, user10 = sess.query(User).all() expected = [ (user7, 1, "Name:jack"), (user8, 3, "Name:ed"), diff --git a/test/orm/test_joins.py b/test/orm/test_joins.py index ff684d846b..75973f1bec 100644 --- a/test/orm/test_joins.py +++ b/test/orm/test_joins.py @@ -1389,8 +1389,8 @@ class JoinTest(QueryTest, AssertsCompiledSQL): sess = fixture_session() - (user7, user8, user9, user10) = sess.query(User).all() - (address1, address2, address3, address4, address5) = sess.query( + user7, user8, user9, user10 = sess.query(User).all() + address1, address2, address3, address4, address5 = sess.query( Address ).all() expected = [ @@ -1494,8 +1494,8 @@ class JoinTest(QueryTest, AssertsCompiledSQL): sess = fixture_session() - (order1, order2, order3, order4, order5) = sess.query(Order).all() - (item1, item2, item3, item4, item5) = sess.query(Item).all() + order1, order2, order3, order4, order5 = sess.query(Order).all() + item1, item2, item3, item4, item5 = sess.query(Item).all() expected = [ (order1, item1), (order1, item2), diff --git a/test/orm/test_naturalpks.py b/test/orm/test_naturalpks.py index 7403715492..8e43802098 100644 --- a/test/orm/test_naturalpks.py +++ b/test/orm/test_naturalpks.py @@ -506,7 +506,7 @@ class NaturalPKTest(fixtures.MappedTest): sess.flush() u1.username = "ed" - (ad1, ad2) = sess.query(Address).all() + ad1, ad2 = sess.query(Address).all() eq_([Address(username="jack"), Address(username="jack")], [ad1, ad2]) def go(): diff --git a/test/orm/test_selectable.py b/test/orm/test_selectable.py index d4ea0e2919..9efdbef1b2 100644 --- a/test/orm/test_selectable.py +++ b/test/orm/test_selectable.py @@ -16,7 +16,6 @@ from sqlalchemy.testing.fixtures import fixture_session from sqlalchemy.testing.schema import Column from sqlalchemy.testing.schema import Table - # TODO: more tests mapping to selects diff --git a/test/orm/test_unitofwork.py b/test/orm/test_unitofwork.py index 5473498688..a82ab73cea 100644 --- a/test/orm/test_unitofwork.py +++ b/test/orm/test_unitofwork.py @@ -1195,7 +1195,7 @@ class DefaultTest(fixtures.MappedTest): session.expunge_all() - (h1, h2, h3, h4, h5) = session.query(Hoho).order_by(Hoho.id).all() + h1, h2, h3, h4, h5 = session.query(Hoho).order_by(Hoho.id).all() eq_(h1.hoho, althohoval) eq_(h3.hoho, althohoval) diff --git a/test/perf/invalidate_stresstest.py b/test/perf/invalidate_stresstest.py index 2e11b7ca93..d7ac0aaa4e 100644 --- a/test/perf/invalidate_stresstest.py +++ b/test/perf/invalidate_stresstest.py @@ -7,7 +7,6 @@ import gevent.monkey from sqlalchemy import create_engine from sqlalchemy import event - gevent.monkey.patch_all() # noqa logging.basicConfig() # noqa diff --git a/test/perf/orm2010.py b/test/perf/orm2010.py index 520944c9f0..0a4d878f76 100644 --- a/test/perf/orm2010.py +++ b/test/perf/orm2010.py @@ -13,7 +13,6 @@ from sqlalchemy.orm import declarative_base from sqlalchemy.orm import relationship from sqlalchemy.orm import Session - Base = declarative_base() diff --git a/test/sql/test_compiler.py b/test/sql/test_compiler.py index 0e86565bd9..d7ad8d09e6 100644 --- a/test/sql/test_compiler.py +++ b/test/sql/test_compiler.py @@ -115,7 +115,6 @@ from sqlalchemy.testing import Variation from sqlalchemy.testing.schema import pep435_enum from sqlalchemy.types import UserDefinedType - if TYPE_CHECKING: from sqlalchemy import Select diff --git a/test/sql/test_functions.py b/test/sql/test_functions.py index 8d60bac02e..05efed51a5 100644 --- a/test/sql/test_functions.py +++ b/test/sql/test_functions.py @@ -55,7 +55,6 @@ from sqlalchemy.testing.assertions import expect_warnings from sqlalchemy.testing.engines import all_dialects from sqlalchemy.testing.provision import normalize_sequence - table1 = table( "mytable", column("myid", Integer), diff --git a/test/sql/test_query.py b/test/sql/test_query.py index fedda753b6..7100ffa125 100644 --- a/test/sql/test_query.py +++ b/test/sql/test_query.py @@ -1160,7 +1160,7 @@ class CompoundTest(fixtures.TablesTest): @testing.requires.subqueries def test_union(self, connection): t1, t2, t3 = self.tables("t1", "t2", "t3") - (s1, s2) = ( + s1, s2 = ( select(t1.c.col3.label("col3"), t1.c.col4.label("col4")).where( t1.c.col2.in_(["t1col2r1", "t1col2r2"]), ), @@ -1187,7 +1187,7 @@ class CompoundTest(fixtures.TablesTest): def test_union_ordered(self, connection): t1, t2, t3 = self.tables("t1", "t2", "t3") - (s1, s2) = ( + s1, s2 = ( select(t1.c.col3.label("col3"), t1.c.col4.label("col4")).where( t1.c.col2.in_(["t1col2r1", "t1col2r2"]), ), @@ -1209,7 +1209,7 @@ class CompoundTest(fixtures.TablesTest): def test_union_ordered_alias(self, connection): t1, t2, t3 = self.tables("t1", "t2", "t3") - (s1, s2) = ( + s1, s2 = ( select(t1.c.col3.label("col3"), t1.c.col4.label("col4")).where( t1.c.col2.in_(["t1col2r1", "t1col2r2"]), ), diff --git a/test/sql/test_selectable.py b/test/sql/test_selectable.py index 7d97de94a2..d721819a67 100644 --- a/test/sql/test_selectable.py +++ b/test/sql/test_selectable.py @@ -62,7 +62,6 @@ from sqlalchemy.testing import ne_ from sqlalchemy.testing.assertions import expect_raises_message from sqlalchemy.testing.provision import normalize_sequence - metadata = MetaData() table1 = Table( "table1", diff --git a/test/typing/plain_files/engine/engine_inspection.py b/test/typing/plain_files/engine/engine_inspection.py index 0ca331f189..18476fddf3 100644 --- a/test/typing/plain_files/engine/engine_inspection.py +++ b/test/typing/plain_files/engine/engine_inspection.py @@ -3,7 +3,6 @@ import typing from sqlalchemy import create_engine from sqlalchemy import inspect - e = create_engine("sqlite://") insp = inspect(e) diff --git a/test/typing/plain_files/ext/asyncio/async_stuff.py b/test/typing/plain_files/ext/asyncio/async_stuff.py index 9afd0b8aff..5b06ca7e78 100644 --- a/test/typing/plain_files/ext/asyncio/async_stuff.py +++ b/test/typing/plain_files/ext/asyncio/async_stuff.py @@ -6,7 +6,6 @@ from sqlalchemy.ext.asyncio import async_sessionmaker from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import create_async_engine - engine = create_async_engine("") SM = async_sessionmaker(engine, class_=AsyncSession) diff --git a/test/typing/plain_files/orm/sessionmakers.py b/test/typing/plain_files/orm/sessionmakers.py index 60d2e8b33e..500b2e0351 100644 --- a/test/typing/plain_files/orm/sessionmakers.py +++ b/test/typing/plain_files/orm/sessionmakers.py @@ -12,7 +12,6 @@ from sqlalchemy.orm import scoped_session from sqlalchemy.orm import Session from sqlalchemy.orm import sessionmaker - async_engine = create_async_engine("...") diff --git a/test/typing/plain_files/orm/traditional_relationship.py b/test/typing/plain_files/orm/traditional_relationship.py index b87e0524c1..dbf1bbde70 100644 --- a/test/typing/plain_files/orm/traditional_relationship.py +++ b/test/typing/plain_files/orm/traditional_relationship.py @@ -20,7 +20,6 @@ from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column from sqlalchemy.orm import relationship - if TYPE_CHECKING: from sqlalchemy.orm import InstrumentedAttribute diff --git a/test/typing/plain_files/orm/typed_queries.py b/test/typing/plain_files/orm/typed_queries.py index 677a79069e..71b24e11e4 100644 --- a/test/typing/plain_files/orm/typed_queries.py +++ b/test/typing/plain_files/orm/typed_queries.py @@ -27,7 +27,6 @@ from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column from sqlalchemy.orm import Session - if TYPE_CHECKING: from sqlalchemy import Row from sqlalchemy.orm.query import RowReturningQuery diff --git a/test/typing/plain_files/sql/core_ddl.py b/test/typing/plain_files/sql/core_ddl.py index 03d827ea7e..0f364fa71d 100644 --- a/test/typing/plain_files/sql/core_ddl.py +++ b/test/typing/plain_files/sql/core_ddl.py @@ -16,7 +16,6 @@ from sqlalchemy import text from sqlalchemy import true from sqlalchemy import UUID - m = MetaData() diff --git a/test/typing/plain_files/sql/sql_operations.py b/test/typing/plain_files/sql/sql_operations.py index 278e2c9a88..2f0be66e82 100644 --- a/test/typing/plain_files/sql/sql_operations.py +++ b/test/typing/plain_files/sql/sql_operations.py @@ -14,7 +14,6 @@ from sqlalchemy import select from sqlalchemy import String from sqlalchemy import true - # builtin.pyi stubs define object.__eq__() as returning bool, which # can't be overridden (it's final). So for us to type `__eq__()` and # `__ne__()`, we have to use type: ignore[override]. Test if does this mean diff --git a/tools/format_docs_code.py b/tools/format_docs_code.py index 056e7ef702..de97298496 100644 --- a/tools/format_docs_code.py +++ b/tools/format_docs_code.py @@ -25,7 +25,6 @@ from black.files import parse_pyproject_toml from black.mode import Mode from black.mode import TargetVersion - home = Path(__file__).parent.parent include_paths = ( re.compile(r"lib/sqlalchemy"), diff --git a/tools/generate_proxy_methods.py b/tools/generate_proxy_methods.py index b9f9d572b0..0eae55e8bd 100644 --- a/tools/generate_proxy_methods.py +++ b/tools/generate_proxy_methods.py @@ -273,28 +273,22 @@ def process_class( metadata["after_line"] = "" if clslevel: - code = ( - '''\ + code = '''\ @classmethod %(async)sdef %(name)s%(grouped_args)s: r"""%(doc)s\n """ # noqa: E501 %(line_prefix)s %(await)s%(target_cls_name)s.%(name)s(%(apply_kw_proxied)s) %(after_line)s -''' - % metadata - ) +''' % metadata else: - code = ( - '''\ + code = '''\ %(async)sdef %(name)s%(grouped_args)s: r"""%(doc)s\n """ # noqa: E501 %(line_prefix)s %(await)s%(self_arg)s._proxied.%(name)s(%(apply_kw_proxied)s) %(after_line)s -''' # noqa: E501 - % metadata - ) +''' % metadata # noqa: E501 buf.write(textwrap.indent(code, " ")) diff --git a/tools/trace_orm_adapter.py b/tools/trace_orm_adapter.py index 72bb08cc48..734264a5db 100644 --- a/tools/trace_orm_adapter.py +++ b/tools/trace_orm_adapter.py @@ -37,7 +37,6 @@ from typing import TYPE_CHECKING from sqlalchemy.orm import util - if TYPE_CHECKING: from typing import Any from typing import List diff --git a/tox.ini b/tox.ini index f94bd3b674..80d47d27ae 100644 --- a/tox.ini +++ b/tox.ini @@ -263,7 +263,7 @@ deps= # in case it requires a version pin pydocstyle pygments - black==25.11.0 + black==26.3.1 slotscheck>=0.17.0 # required by generate_tuple_map_overloads