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=1e1c0084b1804eaae8b7f089435241a2b8f4be60;p=thirdparty%2Fsqlalchemy%2Fsqlalchemy.git update to black 26.3.1 Closes: #13280 Change-Id: Ifbb77dd6d2a1c228ae97fcf8160f40e975edc57c --- diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 07d00fbfb0..bf95187374 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,7 +4,7 @@ default_language_version: repos: - repo: https://github.com/python/black - rev: 25.11.0 + rev: 26.3.1 hooks: - id: black @@ -41,4 +41,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 670daac7ef..defbc0305e 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 6b634ab3bb..d13046305a 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:: @@ -2720,7 +2722,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 ec2dbec2c9..d1f133f40d 100644 --- a/doc/build/orm/dataclasses.rst +++ b/doc/build/orm/dataclasses.rst @@ -103,7 +103,6 @@ decorator is supported:: from sqlalchemy.orm import mapped_column from sqlalchemy.orm import registry - reg = registry() @@ -122,7 +121,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() @@ -173,7 +171,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 9064a4da69..6a6781b26c 100644 --- a/doc/build/orm/declarative_tables.rst +++ b/doc/build/orm/declarative_tables.rst @@ -1105,7 +1105,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, @@ -2226,7 +2225,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 eed7b497a9..a6d543da3c 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/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 3ad714921c..64ce592407 100644 --- a/lib/sqlalchemy/dialects/mssql/__init__.py +++ b/lib/sqlalchemy/dialects/mssql/__init__.py @@ -46,7 +46,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 1dda1e9dc6..e6c7ceda70 100644 --- a/lib/sqlalchemy/dialects/mssql/base.py +++ b/lib/sqlalchemy/dialects/mssql/base.py @@ -3271,8 +3271,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' @@ -3283,10 +3282,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 " @@ -3484,8 +3480,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, @@ -3505,8 +3500,7 @@ where and ind.type != 0 order by ind.name - """ - ) + """) .bindparams( sql.bindparam("tabname", tablename, ischema.CoerceUnicode()), sql.bindparam("schname", owner, ischema.CoerceUnicode()), @@ -3534,8 +3528,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, @@ -3555,8 +3548,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()), @@ -3982,8 +3974,7 @@ order by ): # Foreign key constraints s = ( - text( - """\ + text("""\ WITH fk_info AS ( SELECT ischema_ref_con.constraint_schema, @@ -4083,8 +4074,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 07b9eef60b..f1bfbb5679 100644 --- a/lib/sqlalchemy/dialects/mssql/pyodbc.py +++ b/lib/sqlalchemy/dialects/mssql/pyodbc.py @@ -357,7 +357,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 09db0d7b48..19c59d18d0 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 a7fa2f7d78..b46d9cecd8 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 908d1b5cb0..17978e574e 100644 --- a/lib/sqlalchemy/dialects/mysql/base.py +++ b/lib/sqlalchemy/dialects/mysql/base.py @@ -1062,6 +1062,7 @@ output: ) """ # noqa + from __future__ import annotations from collections import defaultdict 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/mariadbconnector.py b/lib/sqlalchemy/dialects/mysql/mariadbconnector.py index fc26974b82..2c17b7b5f9 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 6ace9bb303..f8ba689b0a 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 bdcc5c010d..c45d9bf49f 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 a9be4ed414..2b8d65bf18 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 8198f8c7da..bca724eb25 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 bf72ec02e4..d5ac03a513 100644 --- a/lib/sqlalchemy/dialects/mysql/reflection.py +++ b/lib/sqlalchemy/dialects/mysql/reflection.py @@ -368,7 +368,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 6a1c86cb89..83491e111d 100644 --- a/lib/sqlalchemy/dialects/oracle/cx_oracle.py +++ b/lib/sqlalchemy/dialects/oracle/cx_oracle.py @@ -467,6 +467,7 @@ SQL statements that are not otherwise associated with a :class:`.Numeric` SQLAlchemy type (or a subclass of such). """ # noqa + from __future__ import annotations import decimal diff --git a/lib/sqlalchemy/dialects/oracle/json.py b/lib/sqlalchemy/dialects/oracle/json.py index 51e9ba872e..b4c528cae1 100644 --- a/lib/sqlalchemy/dialects/oracle/json.py +++ b/lib/sqlalchemy/dialects/oracle/json.py @@ -17,7 +17,6 @@ from ...sql.base import _NoArg from ...sql.base import NO_ARG from ...sql.sqltypes import _T_JSON - if TYPE_CHECKING: from ...engine.interfaces import Dialect from ...sql.type_api import _BindProcessorType diff --git a/lib/sqlalchemy/dialects/oracle/oracledb.py b/lib/sqlalchemy/dialects/oracle/oracledb.py index 5ba4e0ae6c..e76ca13c69 100644 --- a/lib/sqlalchemy/dialects/oracle/oracledb.py +++ b/lib/sqlalchemy/dialects/oracle/oracledb.py @@ -587,6 +587,7 @@ behavioral changes particularly when using the native JSON datatype. See """ # noqa + from __future__ import annotations import collections diff --git a/lib/sqlalchemy/dialects/oracle/vector.py b/lib/sqlalchemy/dialects/oracle/vector.py index 66e439c778..f2cbe93102 100644 --- a/lib/sqlalchemy/dialects/oracle/vector.py +++ b/lib/sqlalchemy/dialects/oracle/vector.py @@ -316,12 +316,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 55dc41400c..76b2f488fa 100644 --- a/lib/sqlalchemy/dialects/postgresql/__init__.py +++ b/lib/sqlalchemy/dialects/postgresql/__init__.py @@ -91,7 +91,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/hstore.py b/lib/sqlalchemy/dialects/postgresql/hstore.py index 91666e71ce..738c27814a 100644 --- a/lib/sqlalchemy/dialects/postgresql/hstore.py +++ b/lib/sqlalchemy/dialects/postgresql/hstore.py @@ -22,7 +22,6 @@ from ... import types as sqltypes from ...sql import functions as sqlfunc from ...types import OperatorClass - __all__ = ("HSTORE", "hstore") _HSTORE_VAL = dict[str, str | None] diff --git a/lib/sqlalchemy/dialects/postgresql/operators.py b/lib/sqlalchemy/dialects/postgresql/operators.py index 2eb4f43138..562eb821e9 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 93cd7e156c..fc1e65e66d 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 @@ -588,11 +589,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 5422849e82..46d7bbf5b5 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 import collections diff --git a/lib/sqlalchemy/dialects/postgresql/psycopg2.py b/lib/sqlalchemy/dialects/postgresql/psycopg2.py index bde9e1c93e..6035c79ed9 100644 --- a/lib/sqlalchemy/dialects/postgresql/psycopg2.py +++ b/lib/sqlalchemy/dialects/postgresql/psycopg2.py @@ -483,6 +483,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 0353b39e82..5be6aa3a63 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 c37bcbb374..a1c4cc8d35 100644 --- a/lib/sqlalchemy/dialects/sqlite/base.py +++ b/lib/sqlalchemy/dialects/sqlite/base.py @@ -844,13 +844,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 ] @@ -885,13 +883,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 @@ -984,6 +980,7 @@ passed to methods such as :meth:`_schema.MetaData.reflect` or documentation. ''' # noqa + from __future__ import annotations import datetime @@ -2595,7 +2592,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 366ca2e460..01ec141ad2 100644 --- a/lib/sqlalchemy/dialects/sqlite/pysqlite.py +++ b/lib/sqlalchemy/dialects/sqlite/pysqlite.py @@ -390,6 +390,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/base.py b/lib/sqlalchemy/engine/base.py index 7f8af56a8c..ba69b471d2 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 47a7a510d7..08d8ffe09e 100644 --- a/lib/sqlalchemy/engine/create.py +++ b/lib/sqlalchemy/engine/create.py @@ -615,7 +615,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", {})) # look for existing pool or create diff --git a/lib/sqlalchemy/engine/cursor.py b/lib/sqlalchemy/engine/cursor.py index ef264ec559..1fd66aa9ee 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 TupleAny from ..util.typing import TypeVarTuple from ..util.typing import Unpack - 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 19ab95d321..9d43059cbc 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 datetime diff --git a/lib/sqlalchemy/engine/reflection.py b/lib/sqlalchemy/engine/reflection.py index 21ea03463e..48418f2fe9 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 08cf350d28..8616b9b79a 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 c4601b9d6b..3db364887d 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 78e041b95a..ed400aa9a7 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 a8d794f897..ff42bc9dcb 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 722f3d6b3c..595e49d613 100644 --- a/lib/sqlalchemy/ext/asyncio/engine.py +++ b/lib/sqlalchemy/ext/asyncio/engine.py @@ -193,7 +193,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 69c98c57bb..82e8c06eac 100644 --- a/lib/sqlalchemy/ext/asyncio/session.py +++ b/lib/sqlalchemy/ext/asyncio/session.py @@ -45,7 +45,6 @@ from ...util.typing import TupleAny from ...util.typing import TypeVarTuple from ...util.typing import Unpack - 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 35af5ed8d2..99b5090d67 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 fd88556c83..89a679ba51 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 7b5c81b391..659e3a3dae 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 02cdd66d69..3fafda9b4d 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 @@ -54,7 +55,6 @@ from ..util.typing import TupleAny from ..util.typing import TypeVarTuple from ..util.typing import Unpack - if TYPE_CHECKING: from ..engine.base import Connection from ..engine.base import Engine diff --git a/lib/sqlalchemy/ext/instrumentation.py b/lib/sqlalchemy/ext/instrumentation.py index 392201dbcd..c42e2bdd25 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/orderinglist.py b/lib/sqlalchemy/ext/orderinglist.py index 83a3e5c462..dfe34d917d 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 68126dad2a..e4252cb503 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 03dbb59412..2758a527bd 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 65919c982c..7250d73ba5 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 @@ -32,7 +33,6 @@ from typing import Union from .util import py311 - STACKLEVEL = True # needed as of py3.11.0b1 # #8019 diff --git a/lib/sqlalchemy/orm/collections.py b/lib/sqlalchemy/orm/collections.py index 4425962379..19eb3ddbfc 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 d5c20f0d00..d09956537d 100644 --- a/lib/sqlalchemy/orm/context.py +++ b/lib/sqlalchemy/orm/context.py @@ -2702,7 +2702,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 2c6158dd3f..3abe01d703 100644 --- a/lib/sqlalchemy/orm/dependency.py +++ b/lib/sqlalchemy/orm/dependency.py @@ -194,7 +194,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 ae810de388..47b0469884 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 @@ -63,7 +64,6 @@ from ..util.typing import is_union from ..util.typing import TupleAny from ..util.typing import Unpack - 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 b7ed1c9399..71fd0f0065 100644 --- a/lib/sqlalchemy/orm/dynamic.py +++ b/lib/sqlalchemy/orm/dynamic.py @@ -45,7 +45,6 @@ from .writeonly import WriteOnlyHistory 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 c97c3d9445..10438a0bcf 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 6f734e8b86..e32bfa4914 100644 --- a/lib/sqlalchemy/orm/instrumentation.py +++ b/lib/sqlalchemy/orm/instrumentation.py @@ -23,7 +23,6 @@ alternate instrumentation forms. """ - from __future__ import annotations from typing import Any diff --git a/lib/sqlalchemy/orm/interfaces.py b/lib/sqlalchemy/orm/interfaces.py index b17fb0af12..9e8ec5dae2 100644 --- a/lib/sqlalchemy/orm/interfaces.py +++ b/lib/sqlalchemy/orm/interfaces.py @@ -77,7 +77,6 @@ from ..util.typing import RODescriptorReference from ..util.typing import TupleAny from ..util.typing import Unpack - if typing.TYPE_CHECKING: from ._typing import _EntityType from ._typing import _IdentityKeyType diff --git a/lib/sqlalchemy/orm/loading.py b/lib/sqlalchemy/orm/loading.py index ad7fabb0f8..73b5bce29b 100644 --- a/lib/sqlalchemy/orm/loading.py +++ b/lib/sqlalchemy/orm/loading.py @@ -112,7 +112,7 @@ def instances( ) try: - (process, labels, extra) = list( + process, labels, extra = list( zip( *[ query_entity.row_processor(context, cursor) @@ -560,7 +560,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 22528a4240..71bb459294 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 674ac91dbe..7037a6b2d7 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 bb3d769424..e6314b5b3d 100644 --- a/lib/sqlalchemy/orm/properties.py +++ b/lib/sqlalchemy/orm/properties.py @@ -950,10 +950,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 38ee0297c3..613625400c 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 @@ -99,7 +100,6 @@ from ..util.typing import TupleAny from ..util.typing import TypeVarTuple from ..util.typing import Unpack - 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 894cde4936..22100e9ea6 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 0aa6458f97..a3be009fec 100644 --- a/lib/sqlalchemy/orm/session.py +++ b/lib/sqlalchemy/orm/session.py @@ -96,7 +96,6 @@ from ..util.typing import TupleAny from ..util.typing import TypeVarTuple from ..util.typing import Unpack - if typing.TYPE_CHECKING: from ._typing import _EntityType from ._typing import _IdentityKeyType @@ -4935,7 +4934,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 3dfbc58ebd..bf63aff9da 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 @@ -523,7 +522,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) @@ -609,7 +608,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 2807acfd7e..f8dd82a48f 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 06ea37900f..f5f602dbcd 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 typing import Literal diff --git a/lib/sqlalchemy/sql/_util_cy.py b/lib/sqlalchemy/sql/_util_cy.py index 7272bfefc3..6b254d33f6 100644 --- a/lib/sqlalchemy/sql/_util_cy.py +++ b/lib/sqlalchemy/sql/_util_cy.py @@ -119,9 +119,9 @@ class anon_map(Dict[_AM_KEY, _AM_VALUE]): self_dict: dict = self # type: ignore[type-arg] if key in self_dict: - return self_dict[key] # type:ignore[no-any-return] + return self_dict[key] # type: ignore[no-any-return] else: - return self._add_missing(key) # type:ignore[no-any-return] + return self._add_missing(key) # type: ignore[no-any-return] def __missing__(self: anon_map, key: _AM_KEY, /) -> int: - return self._add_missing(key) # type:ignore[no-any-return] + return self._add_missing(key) # type: ignore[no-any-return] diff --git a/lib/sqlalchemy/sql/base.py b/lib/sqlalchemy/sql/base.py index 56bde75a12..6f321c2cdd 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 b8781d00ba..4014fbf40b 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 @@ -2196,7 +2197,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 66bd494eae..793e465e0d 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 @@ -911,7 +912,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 45e62848b7..be40cdf877 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 @@ -46,7 +47,6 @@ from .. import util from ..util import topological from ..util.typing import Self - if typing.TYPE_CHECKING: from .compiler import Compiled from .compiler import DDLCompiler diff --git a/lib/sqlalchemy/sql/dml.py b/lib/sqlalchemy/sql/dml.py index 2dbdf2bc16..d44a5d5e14 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 @@ -76,7 +77,6 @@ from ..util.typing import TupleAny from ..util.typing import TypeVarTuple from ..util.typing import Unpack - if TYPE_CHECKING: from ._typing import _ColumnExpressionArgument from ._typing import _ColumnsClauseArgument diff --git a/lib/sqlalchemy/sql/elements.py b/lib/sqlalchemy/sql/elements.py index 12b9eeefb7..acfeadced6 100644 --- a/lib/sqlalchemy/sql/elements.py +++ b/lib/sqlalchemy/sql/elements.py @@ -86,7 +86,6 @@ from ..util.typing import Self from ..util.typing import TupleAny from ..util.typing import Unpack - 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 06e20c1a4e..90efdc4241 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 497e797e1a..38fa97b0e3 100644 --- a/lib/sqlalchemy/sql/lambdas.py +++ b/lib/sqlalchemy/sql/lambdas.py @@ -45,7 +45,6 @@ from .. import exc from .. import inspection from .. import util - if TYPE_CHECKING: from .elements import BindParameter from .elements import ClauseElement @@ -302,7 +301,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 ab309765a3..14958cc27b 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 @@ -2632,11 +2633,9 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T], Named[_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 eb09cfa3a6..cc29ebdbec 100644 --- a/lib/sqlalchemy/sql/selectable.py +++ b/lib/sqlalchemy/sql/selectable.py @@ -5221,7 +5221,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 48c5b00d7e..c5a11f5dbd 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 @@ -3798,7 +3799,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 efa39eab63..99d3219c10 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 652a73d88d..9b129ae499 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 @@ -864,7 +865,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 80a3376897..288f1b76f7 100644 --- a/lib/sqlalchemy/testing/engines.py +++ b/lib/sqlalchemy/testing/engines.py @@ -27,7 +27,6 @@ from .. import event from .. import pool from ..util import await_ - 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 c712c9e460..44576b2a16 100644 --- a/lib/sqlalchemy/testing/fixtures/mypy.py +++ b/lib/sqlalchemy/testing/fixtures/mypy.py @@ -50,8 +50,7 @@ class MypyTest(TestBase): 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} @@ -59,8 +58,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 a4262f38b4..391b24576b 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 0f53db6463..a283419d3a 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 13722beb69..4374622c5a 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 0872072f7c..53e130b8c5 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 db46c63c12..67567992b4 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.operators import OperatorClass as OperatorClass diff --git a/lib/sqlalchemy/util/_collections.py b/lib/sqlalchemy/util/_collections.py index 432d68e3f3..2034d92a23 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 @@ -45,7 +46,6 @@ from ._immutabledict_cy import ImmutableDictBase as ImmutableDictBase from ._immutabledict_cy import ReadOnlyContainer as ReadOnlyContainer from .typing import is_non_string_iterable - _T = TypeVar("_T", bound=Any) _KT = TypeVar("_KT", bound=Any) _VT = TypeVar("_VT", bound=Any) diff --git a/lib/sqlalchemy/util/langhelpers.py b/lib/sqlalchemy/util/langhelpers.py index 50a22026f2..fdf539f7bb 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 @@ -318,21 +319,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, @@ -1654,9 +1649,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 @@ -1956,7 +1955,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 b6350b88b6..04509f98dd 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 2e543df2d6..7547cad5c9 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 @@ -33,7 +34,6 @@ from typing import TypeVar from .concurrency import await_ 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 9c03972be5..1c043ecd50 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -185,7 +185,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 5c6ef2b1dd..84527826fd 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 4ccdd29b2d..754478c982 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 90597d8882..5a24c3c08c 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 ce642b00ef..63e2c4e4c0 100644 --- a/test/dialect/mssql/test_query.py +++ b/test/dialect/mssql/test_query.py @@ -457,20 +457,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( @@ -628,8 +624,7 @@ class TableValuedTest(fixtures.TestBase): @testing.fixture def scalar_strings(self, connection): - connection.exec_driver_sql( - """ + connection.exec_driver_sql(""" CREATE FUNCTION scalar_strings ( ) @@ -641,15 +636,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 @@ -660,8 +653,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 2b6bd5f5bf..1cc41e453f 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( @@ -1108,8 +1106,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 @@ -1126,31 +1123,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 @@ -1161,8 +1152,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 265857e013..70708857b7 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) @@ -782,9 +776,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} @@ -1034,20 +1026,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 = [ { @@ -1172,13 +1158,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 57e795ad3a..fa1fb457db 100644 --- a/test/dialect/postgresql/test_reflection.py +++ b/test/dialect/postgresql/test_reflection.py @@ -1719,34 +1719,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 = [ { @@ -1890,28 +1884,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() @@ -2176,19 +2164,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 5118687485..1673916c61 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 ab5cdccd8b..d61937f964 100644 --- a/test/engine/test_pool.py +++ b/test/engine/test_pool.py @@ -478,10 +478,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/test_extendedattr.py b/test/ext/test_extendedattr.py index 403d2dd41c..3eb32e6670 100644 --- a/test/ext/test_extendedattr.py +++ b/test/ext/test_extendedattr.py @@ -403,7 +403,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 c56d2cafc2..60cd3f14ae 100644 --- a/test/orm/declarative/test_basic.py +++ b/test/orm/declarative/test_basic.py @@ -70,7 +70,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 e01805ce70..2c027642b7 100644 --- a/test/orm/declarative/test_tm_future_annotations_sync.py +++ b/test/orm/declarative/test_tm_future_annotations_sync.py @@ -103,7 +103,6 @@ from sqlalchemy.testing import Variation from sqlalchemy.testing.assertions import ne_ from sqlalchemy.testing.fixtures import fixture_session - # 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 d5d5298a9f..0d2c6cdc33 100644 --- a/test/orm/declarative/test_typed_mapping.py +++ b/test/orm/declarative/test_typed_mapping.py @@ -94,7 +94,6 @@ from sqlalchemy.testing import Variation from sqlalchemy.testing.assertions import ne_ from sqlalchemy.testing.fixtures import fixture_session - # 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 bce3667e4b..4310c49ec6 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 c67269c6c7..a51192a9d5 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 2713b5572c..211ed8694d 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 1dd7037515..50eb4cf75c 100644 --- a/test/sql/test_compiler.py +++ b/test/sql/test_compiler.py @@ -118,7 +118,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 7d0bf5c241..b7969858ae 100644 --- a/test/sql/test_functions.py +++ b/test/sql/test_functions.py @@ -65,7 +65,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 7762ab8637..0a0a738e53 100644 --- a/test/sql/test_query.py +++ b/test/sql/test_query.py @@ -1092,7 +1092,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"]), ), @@ -1119,7 +1119,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"]), ), @@ -1141,7 +1141,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 191ad66369..80c87da0f9 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 0660f44380..cc6ed2e2b6 100644 --- a/test/typing/plain_files/engine/engine_inspection.py +++ b/test/typing/plain_files/engine/engine_inspection.py @@ -7,7 +7,6 @@ from sqlalchemy.engine import Inspector from sqlalchemy.engine.base import Engine from sqlalchemy.engine.interfaces import ReflectedColumn - 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 8e959cea98..f597d60ff9 100644 --- a/test/typing/plain_files/orm/sessionmakers.py +++ b/test/typing/plain_files/orm/sessionmakers.py @@ -15,7 +15,6 @@ from sqlalchemy.orm import Session from sqlalchemy.orm import sessionmaker from sqlalchemy.orm.query import Query - async_engine = create_async_engine("...") 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 ef3b2dc390..e762d613ba 100644 --- a/test/typing/plain_files/sql/sql_operations.py +++ b/test/typing/plain_files/sql/sql_operations.py @@ -21,7 +21,6 @@ from sqlalchemy.sql.elements import UnaryExpression from sqlalchemy.sql.expression import BinaryExpression from sqlalchemy.sql.expression import ColumnClause - # 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/test/typing/plain_files/sql/sqltypes.py b/test/typing/plain_files/sql/sqltypes.py index 7240b7c0d5..3e4c93e66f 100644 --- a/test/typing/plain_files/sql/sqltypes.py +++ b/test/typing/plain_files/sql/sqltypes.py @@ -9,7 +9,6 @@ from sqlalchemy import Select from sqlalchemy import select from sqlalchemy.sql.sqltypes import _JSON_VALUE - assert_type(Float(), Float[float]) assert_type(Float(asdecimal=True), Float[Decimal]) 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 95bb1a4180..174f6d541a 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 484e4055db..4aa5facea5 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