From: Mike Bayer Date: Mon, 20 Jul 2026 16:52:20 +0000 (-0400) Subject: Enable mypy ignore-without-code rule X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=ea3f59299e3e02a688eee8407738a31a3fd5bacc;p=thirdparty%2Fsqlalchemy%2Fsqlalchemy.git Enable mypy ignore-without-code rule Enable the mypy ``ignore-without-code`` error code in ``pyproject.toml`` so that bare ``# type: ignore`` comments are rejected, and add the specific error code reported by mypy to each of the 330 remaining bare ignore comments across 73 modules in ``lib/sqlalchemy``. Codes were derived by running mypy against current main and applying the code it reported for each location (e.g. ``[assignment]``, ``[no-any-return]``, ``[union-attr]``), rather than carrying over codes from an earlier branch, since the underlying types and the set of ignores already present on main have diverged substantially. 71 lines that became longer than 79 characters after adding the code were annotated with ``# noqa: E501``, matching the existing convention used elsewhere in the codebase. Change-Id: I5b32b5edc3de382b426b7b297adbf522a7998538 --- diff --git a/lib/sqlalchemy/connectors/asyncio.py b/lib/sqlalchemy/connectors/asyncio.py index 5a4fc7cc31..f968f753d4 100644 --- a/lib/sqlalchemy/connectors/asyncio.py +++ b/lib/sqlalchemy/connectors/asyncio.py @@ -337,7 +337,7 @@ class AsyncAdapt_dbapi_ss_cursor(AsyncAdapt_dbapi_cursor): def close(self) -> None: if self._cursor is not None: await_(self._cursor.close()) - self._cursor = None # type: ignore + self._cursor = None # type: ignore[assignment] def fetchone(self) -> Optional[Any]: return await_(self._cursor.fetchone()) diff --git a/lib/sqlalchemy/dialects/__init__.py b/lib/sqlalchemy/dialects/__init__.py index d6336c1aa5..ef065a5c35 100644 --- a/lib/sqlalchemy/dialects/__init__.py +++ b/lib/sqlalchemy/dialects/__init__.py @@ -43,7 +43,7 @@ def _auto_fn(name: str) -> Optional[Callable[[], Type[Dialect]]]: module: Any = __import__( "sqlalchemy.dialects.mysql.mariadb" ).dialects.mysql.mariadb - return module.loader(driver) # type: ignore + return module.loader(driver) # type: ignore[no-any-return] else: module = __import__("sqlalchemy.dialects.%s" % (dialect,)).dialects module = getattr(module, dialect) diff --git a/lib/sqlalchemy/dialects/mysql/aiomysql.py b/lib/sqlalchemy/dialects/mysql/aiomysql.py index 5f1e675baa..67fca8ee2f 100644 --- a/lib/sqlalchemy/dialects/mysql/aiomysql.py +++ b/lib/sqlalchemy/dialects/mysql/aiomysql.py @@ -104,7 +104,7 @@ class AsyncAdapt_aiomysql_connection( await_(self._connection.autocommit(value)) def get_autocommit(self) -> bool: - return self._connection.get_autocommit() # type: ignore + return self._connection.get_autocommit() # type: ignore[no-any-return] def close(self) -> None: await_(self._connection.ensure_closed()) @@ -238,7 +238,7 @@ class MySQLDialect_aiomysql(MySQLDialect_pymysql): return "not connected" in str_e def _found_rows_client_flag(self) -> int: - from pymysql.constants import CLIENT # type: ignore + from pymysql.constants import CLIENT # type: ignore[import-untyped] return CLIENT.FOUND_ROWS # type: ignore[no-any-return] diff --git a/lib/sqlalchemy/dialects/mysql/asyncmy.py b/lib/sqlalchemy/dialects/mysql/asyncmy.py index 5095c21199..c2b7310273 100644 --- a/lib/sqlalchemy/dialects/mysql/asyncmy.py +++ b/lib/sqlalchemy/dialects/mysql/asyncmy.py @@ -116,7 +116,7 @@ class AsyncAdapt_asyncmy_connection( await_(self._connection.autocommit(value)) def get_autocommit(self) -> bool: - return self._connection.get_autocommit() # type: ignore + return self._connection.get_autocommit() # type: ignore[no-any-return] def close(self) -> None: await_(self._connection.ensure_closed()) @@ -223,7 +223,7 @@ class MySQLDialect_asyncmy(MySQLDialect_pymysql): ) def _found_rows_client_flag(self) -> int: - from asyncmy.constants import CLIENT # type: ignore + from asyncmy.constants import CLIENT # type: ignore[import-not-found] return CLIENT.FOUND_ROWS # type: ignore[no-any-return] diff --git a/lib/sqlalchemy/dialects/mysql/base.py b/lib/sqlalchemy/dialects/mysql/base.py index b9a411e453..1e934a33a9 100644 --- a/lib/sqlalchemy/dialects/mysql/base.py +++ b/lib/sqlalchemy/dialects/mysql/base.py @@ -2976,9 +2976,9 @@ class MySQLDialect(_mariadb_shim.MariaDBShim, default.DefaultDialect): if isinstance( e, ( - self.dbapi.OperationalError, # type: ignore - self.dbapi.ProgrammingError, # type: ignore - self.dbapi.InterfaceError, # type: ignore + self.dbapi.OperationalError, # type: ignore[union-attr] + self.dbapi.ProgrammingError, # type: ignore[union-attr] + self.dbapi.InterfaceError, # type: ignore[union-attr] ), ) and self._extract_error_code(e) in ( 1927, @@ -2991,7 +2991,7 @@ class MySQLDialect(_mariadb_shim.MariaDBShim, default.DefaultDialect): ): return True elif isinstance( - e, (self.dbapi.InterfaceError, self.dbapi.InternalError) # type: ignore # noqa: E501 + e, (self.dbapi.InterfaceError, self.dbapi.InternalError) # type: ignore[union-attr] # noqa: E501 ): # if underlying connection is closed, # this is the error you get @@ -3087,7 +3087,7 @@ class MySQLDialect(_mariadb_shim.MariaDBShim, default.DefaultDialect): # # there's more "doesn't exist" kinds of messages but they are # less clear if mysql 8 would suddenly start using one of those - if self._extract_error_code(e.orig) in (1146, 1049, 1051): # type: ignore # noqa: E501 + if self._extract_error_code(e.orig) in (1146, 1049, 1051): # type: ignore[arg-type, operator] # noqa: E501 return False raise @@ -3224,7 +3224,7 @@ class MySQLDialect(_mariadb_shim.MariaDBShim, default.DefaultDialect): if schema is not None: current_schema: str = schema else: - current_schema = self.default_schema_name # type: ignore + current_schema = self.default_schema_name # type: ignore[assignment] # noqa: E501 charset = self._connection_charset @@ -3385,7 +3385,7 @@ class MySQLDialect(_mariadb_shim.MariaDBShim, default.DefaultDialect): def lower(s: str) -> str: return s - default_schema_name: str = connection.dialect.default_schema_name # type: ignore # noqa: E501 + default_schema_name: str = connection.dialect.default_schema_name # type: ignore[assignment] # noqa: E501 # NOTE: using (table_schema, table_name, lower(column_name)) in (...) # is very slow since mysql does not seem able to properly use indexse. diff --git a/lib/sqlalchemy/dialects/mysql/enumerated.py b/lib/sqlalchemy/dialects/mysql/enumerated.py index 0caffc1edf..ee7ba07d11 100644 --- a/lib/sqlalchemy/dialects/mysql/enumerated.py +++ b/lib/sqlalchemy/dialects/mysql/enumerated.py @@ -257,7 +257,7 @@ class SET(_StringType): if value is not None and not isinstance(value, (int, str)): value = ",".join(value) if super_convert: - return super_convert(value) # type: ignore + return super_convert(value) # type: ignore[arg-type, no-any-return] # noqa: E501 else: return value diff --git a/lib/sqlalchemy/dialects/mysql/mysqlconnector.py b/lib/sqlalchemy/dialects/mysql/mysqlconnector.py index f8ba689b0a..07a657137d 100644 --- a/lib/sqlalchemy/dialects/mysql/mysqlconnector.py +++ b/lib/sqlalchemy/dialects/mysql/mysqlconnector.py @@ -198,7 +198,7 @@ class MySQLDialect_mysqlconnector(MySQLDialect): # supports_sane_rowcount. if self.dbapi is not None: try: - from mysql.connector import constants # type: ignore + from mysql.connector import constants # type: ignore[import-not-found] # noqa: E501 ClientFlag = constants.ClientFlag @@ -221,10 +221,10 @@ class MySQLDialect_mysqlconnector(MySQLDialect): return None def _detect_charset(self, connection: Connection) -> str: - return connection.connection.charset # type: ignore + return connection.connection.charset # type: ignore[no-any-return] def _extract_error_code(self, exception: BaseException) -> int: - return exception.errno # type: ignore + return exception.errno # type: ignore[attr-defined, no-any-return] def is_disconnect( self, diff --git a/lib/sqlalchemy/dialects/mysql/mysqldb.py b/lib/sqlalchemy/dialects/mysql/mysqldb.py index c45d9bf49f..e5dbf2d07a 100644 --- a/lib/sqlalchemy/dialects/mysql/mysqldb.py +++ b/lib/sqlalchemy/dialects/mysql/mysqldb.py @@ -258,7 +258,7 @@ class MySQLDialect_mysqldb(MySQLDialect): except (AttributeError, ImportError): return None else: - return CLIENT_FLAGS.FOUND_ROWS # type: ignore + return CLIENT_FLAGS.FOUND_ROWS # type: ignore[no-any-return] else: return None diff --git a/lib/sqlalchemy/dialects/postgresql/hstore.py b/lib/sqlalchemy/dialects/postgresql/hstore.py index 0a25f1fc9b..243927cbbc 100644 --- a/lib/sqlalchemy/dialects/postgresql/hstore.py +++ b/lib/sqlalchemy/dialects/postgresql/hstore.py @@ -168,7 +168,7 @@ class HSTORE( ) def _setup_getitem(self, index: Any) -> Any: - return GETITEM, index, self.type.text_type # type: ignore + return GETITEM, index, self.type.text_type # type: ignore[attr-defined] # noqa: E501 def defined(self, key: Any) -> Any: """Boolean expression. Test for presence of a non-NULL value for diff --git a/lib/sqlalchemy/dialects/postgresql/ranges.py b/lib/sqlalchemy/dialects/postgresql/ranges.py index 7d423ef012..c410e8d8af 100644 --- a/lib/sqlalchemy/dialects/postgresql/ranges.py +++ b/lib/sqlalchemy/dialects/postgresql/ranges.py @@ -140,13 +140,13 @@ class Range(Generic[_T]): ) if self.upper is None: - return ( # type: ignore + return ( # type: ignore[no-any-return] value > self.lower if self.bounds[0] == "(" else value >= self.lower ) - return ( # type: ignore + return ( # type: ignore[no-any-return] value > self.lower if self.bounds[0] == "(" else value >= self.lower @@ -446,14 +446,14 @@ class Range(Generic[_T]): return False if bound1 == "]": if bound2 == "[": - return value1 == value2 - step # type: ignore + return value1 == value2 - step # type: ignore[no-any-return] # noqa: E501 else: return value1 == value2 else: if bound2 == "[": return value1 == value2 else: - return value1 == value2 - step # type: ignore + return value1 == value2 - step # type: ignore[no-any-return] # noqa: E501 elif res == 0: # Cover cases like [0,0] -|- [1,] and [0,2) -|- (1,3] if ( @@ -673,8 +673,8 @@ class Range(Generic[_T]): return "empty" l, r = self.lower, self.upper - l = "" if l is None else l # type: ignore - r = "" if r is None else r # type: ignore + l = "" if l is None else l # type: ignore[assignment] + r = "" if r is None else r # type: ignore[assignment] b0, b1 = cast("Tuple[str, str]", self.bounds) @@ -750,7 +750,7 @@ class AbstractRange(sqltypes.TypeEngine[_T]): # The adapt() operation here is cached per type-class-per-dialect, # so is not much of a performance concern visit_name = self.__visit_name__ - return type( # type: ignore + return type( # type: ignore[no-any-return] f"{visit_name}RangeImpl", (cls, self.__class__), {"__visit_name__": visit_name}, diff --git a/lib/sqlalchemy/dialects/sqlite/pysqlite.py b/lib/sqlalchemy/dialects/sqlite/pysqlite.py index 66e33cc449..0d22182bf8 100644 --- a/lib/sqlalchemy/dialects/sqlite/pysqlite.py +++ b/lib/sqlalchemy/dialects/sqlite/pysqlite.py @@ -580,7 +580,7 @@ class SQLiteDialect_pysqlite(SQLiteDialect): return pool.SingletonThreadPool def _get_server_version_info(self, connection: Any) -> VersionInfoType: - return self.dbapi.sqlite_version_info # type: ignore + return self.dbapi.sqlite_version_info # type: ignore[no-any-return, union-attr] # noqa: E501 _isolation_lookup = SQLiteDialect._isolation_lookup.union( { diff --git a/lib/sqlalchemy/engine/_result_cy.py b/lib/sqlalchemy/engine/_result_cy.py index 760ed87ec3..3f716b0584 100644 --- a/lib/sqlalchemy/engine/_result_cy.py +++ b/lib/sqlalchemy/engine/_result_cy.py @@ -376,7 +376,7 @@ class BaseResultInternal(Generic[_R]): made_rows, [], uniques, strategy ) else: - interim_rows = made_rows # type: ignore + interim_rows = made_rows # type: ignore[assignment] if post_creational_filter is not None: interim_rows = [ @@ -411,7 +411,7 @@ class BaseResultInternal(Generic[_R]): uniques.add(hashed) if post_creational_filter is not None: obj = post_creational_filter(obj) - return obj # type: ignore + return obj # type: ignore[return-value] else: @@ -425,7 +425,7 @@ class BaseResultInternal(Generic[_R]): ) if post_creational_filter is not None: interim_row = post_creational_filter(interim_row) - return interim_row # type: ignore + return interim_row # type: ignore[return-value] return onerow @@ -612,9 +612,9 @@ class BaseResultInternal(Generic[_R]): row = post_creational_filter(row) if scalar and make_row is not None: - return row[0] # type: ignore + return row[0] # type: ignore[no-any-return] else: - return row # type: ignore + return row # type: ignore[return-value] def _iter_impl(self) -> Iterator[_R]: return self._iterator_getter() diff --git a/lib/sqlalchemy/engine/create.py b/lib/sqlalchemy/engine/create.py index 08d8ffe09e..747ed7999b 100644 --- a/lib/sqlalchemy/engine/create.py +++ b/lib/sqlalchemy/engine/create.py @@ -539,7 +539,7 @@ def create_engine(url: Union[str, _url.URL], **kwargs: Any) -> Engine: strat = kwargs.pop("strategy") if strat == "mock": # this case is deprecated - return create_mock_engine(url, **kwargs) # type: ignore + return create_mock_engine(url, **kwargs) # type: ignore[return-value] # noqa: E501 else: raise exc.ArgumentError("unknown strategy: %r" % strat) @@ -566,7 +566,7 @@ def create_engine(url: Union[str, _url.URL], **kwargs: Any) -> Engine: return value else: - pop_kwarg = kwargs.pop # type: ignore + pop_kwarg = kwargs.pop # type: ignore[assignment] dialect_args = {} # consume dialect arguments from kwargs diff --git a/lib/sqlalchemy/engine/cursor.py b/lib/sqlalchemy/engine/cursor.py index 3ffc9ff133..3649bf6553 100644 --- a/lib/sqlalchemy/engine/cursor.py +++ b/lib/sqlalchemy/engine/cursor.py @@ -401,7 +401,7 @@ class CursorResultMetaData(ResultMetaData): result_columns = tuplefilter(result_columns) num_ctx_cols = len(result_columns) else: - result_columns = cols_are_ordered = ( # type: ignore + result_columns = cols_are_ordered = ( # type: ignore[assignment] num_ctx_cols ) = ad_hoc_textual = loose_column_name_matching = ( textual_ordered @@ -1785,7 +1785,7 @@ class CursorResult(Result[Unpack[_Ts]]): if not self._soft_closed: cursor = self.cursor - self.cursor = None # type: ignore + self.cursor = None # type: ignore[assignment] self.connection._safe_close_cursor(cursor) self._soft_closed = True diff --git a/lib/sqlalchemy/engine/default.py b/lib/sqlalchemy/engine/default.py index 05dd336d47..99d0d6b843 100644 --- a/lib/sqlalchemy/engine/default.py +++ b/lib/sqlalchemy/engine/default.py @@ -433,7 +433,7 @@ class DefaultDialect(Dialect): use_insertmanyvalues: Optional[bool] = None, # util.deprecated_params decorator cannot render the # Linting.NO_LINTING constant - compiler_linting: Linting = int(compiler.NO_LINTING), # type: ignore + compiler_linting: Linting = int(compiler.NO_LINTING), # type: ignore[assignment] # noqa: E501 server_side_cursors: bool = False, skip_autocommit_rollback: bool = False, **kwargs: Any, @@ -1481,7 +1481,7 @@ class DefaultExecutionContext(ExecutionContext): self.is_text = compiled.isplaintext if ii or iu or id_: - dml_statement = compiled.compile_state.statement # type: ignore + dml_statement = compiled.compile_state.statement # type: ignore[union-attr] # noqa: E501 if TYPE_CHECKING: assert isinstance(dml_statement, UpdateBase) self.is_crud = True @@ -1595,7 +1595,7 @@ class DefaultExecutionContext(ExecutionContext): self._expanded_parameters = expanded_state.parameter_expansion - flattened_processors = dict(processors) # type: ignore + flattened_processors = dict(processors) # type: ignore[arg-type] flattened_processors.update(expanded_state.processors) positiontup = expanded_state.positiontup elif compiled.positional: @@ -2341,7 +2341,7 @@ class DefaultExecutionContext(ExecutionContext): parameters = self.dialect.execute_sequence_format( [ ( - processors[key](compiled_params[key]) # type: ignore + processors[key](compiled_params[key]) # type: ignore[operator] # noqa: E501 if key in processors else compiled_params[key] ) @@ -2351,7 +2351,7 @@ class DefaultExecutionContext(ExecutionContext): else: parameters = { key: ( - processors[key](compiled_params[key]) # type: ignore + processors[key](compiled_params[key]) # type: ignore[assignment, operator] # noqa: E501 if key in processors else compiled_params[key] ) diff --git a/lib/sqlalchemy/engine/events.py b/lib/sqlalchemy/engine/events.py index a6c3b45743..899f438f05 100644 --- a/lib/sqlalchemy/engine/events.py +++ b/lib/sqlalchemy/engine/events.py @@ -163,7 +163,7 @@ class ConnectionEvents(event.Events[ConnectionEventsTarget]): if identifier == "before_execute": orig_fn = fn - def wrap_before_execute( # type: ignore + def wrap_before_execute( # type: ignore[no-untyped-def] conn, clauseelement, multiparams, params, execution_options ): orig_fn( @@ -179,7 +179,7 @@ class ConnectionEvents(event.Events[ConnectionEventsTarget]): elif identifier == "before_cursor_execute": orig_fn = fn - def wrap_before_cursor_execute( # type: ignore + def wrap_before_cursor_execute( # type: ignore[no-untyped-def] conn, cursor, statement, parameters, context, executemany ): orig_fn( diff --git a/lib/sqlalchemy/engine/result.py b/lib/sqlalchemy/engine/result.py index d5f31f8e70..1280182357 100644 --- a/lib/sqlalchemy/engine/result.py +++ b/lib/sqlalchemy/engine/result.py @@ -344,7 +344,7 @@ class SimpleResultMetaData(ResultMetaData): _tuplefilter = tuplegetter(*_translated_indexes) else: _translated_indexes = _tuplefilter = None - self.__init__( # type: ignore + self.__init__( # type: ignore[misc] state["_keys"], _translated_indexes=_translated_indexes, _tuplefilter=_tuplefilter, @@ -808,7 +808,7 @@ class Result(_WithKeys, ResultInternal[Row[Unpack[_Ts]]]): workaround for SQLAlchemy 2.1. """ - return self # type: ignore + return self # type: ignore[return-value] @deprecated( "2.1.0", @@ -842,7 +842,7 @@ class Result(_WithKeys, ResultInternal[Row[Unpack[_Ts]]]): """ - return self # type: ignore + return self # type: ignore[return-value] def _raw_row_iterator(self) -> Iterator[_RowData]: """Return a safe iterator that yields raw row data. @@ -1959,7 +1959,7 @@ class ChunkedIteratorResult(IteratorResult[Unpack[_Ts]]): def _soft_close(self, hard: bool = False, **kw: Any) -> None: super()._soft_close(hard=hard, **kw) - self.chunks = lambda size: [] # type: ignore + self.chunks = lambda size: [] # type: ignore[assignment, return-value] def _fetchmany_impl( self, size: Optional[int] = None diff --git a/lib/sqlalchemy/engine/url.py b/lib/sqlalchemy/engine/url.py index c3f1986bc7..26563b341a 100644 --- a/lib/sqlalchemy/engine/url.py +++ b/lib/sqlalchemy/engine/url.py @@ -914,7 +914,7 @@ def _parse_url(name: str) -> URL: if components["port"]: components["port"] = int(components["port"]) - return URL.create(name, **components) # type: ignore + return URL.create(name, **components) # type: ignore[arg-type] else: raise exc.ArgumentError( diff --git a/lib/sqlalchemy/engine/util.py b/lib/sqlalchemy/engine/util.py index 8cbfe4b029..7e27411857 100644 --- a/lib/sqlalchemy/engine/util.py +++ b/lib/sqlalchemy/engine/util.py @@ -30,7 +30,7 @@ def connection_memoize(key: str) -> Callable[[_C], _C]: """ @util.decorator - def decorated(fn, self, connection): # type: ignore + def decorated(fn, self, connection): # type: ignore[no-untyped-def] connection = connection.connect() try: return connection.info[key] diff --git a/lib/sqlalchemy/ext/associationproxy.py b/lib/sqlalchemy/ext/associationproxy.py index ff42bc9dcb..9651d05380 100644 --- a/lib/sqlalchemy/ext/associationproxy.py +++ b/lib/sqlalchemy/ext/associationproxy.py @@ -416,7 +416,7 @@ class AssociationProxy( id(self), ) if info: - self.info = info # type: ignore + self.info = info # type: ignore[misc] if ( attribute_options @@ -517,9 +517,9 @@ class AssociationProxy( # class, only on subclasses of it, which might be # different. only return for the specific # object's current value - return inst._non_canonical_get_for_object(obj) # type: ignore + return inst._non_canonical_get_for_object(obj) # type: ignore[no-any-return] # noqa: E501 else: - return inst # type: ignore # TODO + return inst # type: ignore[no-any-return] # TODO def _calc_owner(self, target_cls: Any) -> Any: # we might be getting invoked for a subclass @@ -710,7 +710,7 @@ class AssociationProxyInstance(SQLORMOperations[_T]): @property def _comparator(self) -> PropComparator[Any]: - return getattr( # type: ignore + return getattr( # type: ignore[no-any-return] self.owning_class, self.target_collection ).comparator @@ -1307,7 +1307,7 @@ class AliasedAssociationProxyInstance(ObjectAssociationProxyInstance[_T]): @property def _comparator(self) -> PropComparator[Any]: - return getattr( # type: ignore + return getattr( # type: ignore[no-any-return] self.aliased_insp.entity, self.target_collection ).comparator @@ -1762,7 +1762,7 @@ class _AssociationDict(_AssociationCollection[_VT], MutableMapping[_KT, _VT]): # compatible with None.". if key not in self.col: self.col[key] = self._create(key, default) - return default # type: ignore + return default # type: ignore[return-value] else: return self[key] @@ -1927,7 +1927,7 @@ class _AssociationSet(_AssociationSingleItem[_T], MutableSet[_T]): for member in removals: remover(member) - def __ior__( # type: ignore + def __ior__( # type: ignore[override] self, other: AbstractSet[_S] ) -> MutableSet[Union[_T, _S]]: if not collections._set_binops_check_strict(self, other): @@ -2018,7 +2018,7 @@ class _AssociationSet(_AssociationSingleItem[_T], MutableSet[_T]): for value in add: self.add(value) - def __ixor__(self, other: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: # type: ignore # noqa: E501 + def __ixor__(self, other: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: # type: ignore[override] # noqa: E501 if not collections._set_binops_check_strict(self, other): return NotImplemented diff --git a/lib/sqlalchemy/ext/asyncio/base.py b/lib/sqlalchemy/ext/asyncio/base.py index 40ad7d10a8..a6d7890de4 100644 --- a/lib/sqlalchemy/ext/asyncio/base.py +++ b/lib/sqlalchemy/ext/asyncio/base.py @@ -99,7 +99,7 @@ class ReversibleProxy(Generic[_PT]): else: proxy = proxy_ref() if proxy is not None: - return proxy # type: ignore + return proxy # type: ignore[return-value] if regenerate: return cls._regenerate_proxy_for_target(target, **additional_kw) @@ -144,7 +144,7 @@ class GeneratorStartableContext(StartableContext[_T_co]): args: Tuple[Any, ...], kwds: Dict[str, Any], ): - self.gen = func(*args, **kwds) # type: ignore + self.gen = func(*args, **kwds) # type: ignore[assignment] async def start(self, is_ctxmanager: bool = False) -> _T_co: try: diff --git a/lib/sqlalchemy/ext/asyncio/engine.py b/lib/sqlalchemy/ext/asyncio/engine.py index 595e49d613..ee9ccc6da7 100644 --- a/lib/sqlalchemy/ext/asyncio/engine.py +++ b/lib/sqlalchemy/ext/asyncio/engine.py @@ -118,7 +118,7 @@ def create_async_engine(url: Union[str, URL], **kw: Any) -> AsyncEngine: # note that to send adapted arguments like # prepared_statement_cache_size, user would use # "creator" and emulate this form here - return sync_engine.dialect.dbapi.connect( # type: ignore + return sync_engine.dialect.dbapi.connect( # type: ignore[union-attr] # noqa: E501 async_creator_fn=async_creator ) diff --git a/lib/sqlalchemy/ext/asyncio/result.py b/lib/sqlalchemy/ext/asyncio/result.py index f3167f93d4..d2f97586a7 100644 --- a/lib/sqlalchemy/ext/asyncio/result.py +++ b/lib/sqlalchemy/ext/asyncio/result.py @@ -127,7 +127,7 @@ class AsyncResult(_WithKeys, AsyncCommon[Row[Unpack[_Ts]]]): workaround for SQLAlchemy 2.1. """ - return self # type: ignore + return self # type: ignore[return-value] @deprecated( "2.1.0", @@ -162,7 +162,7 @@ class AsyncResult(_WithKeys, AsyncCommon[Row[Unpack[_Ts]]]): """ - return self # type: ignore + return self # type: ignore[return-value] @_generative def unique(self, strategy: Optional[_UniqueFilterType] = None) -> Self: @@ -972,9 +972,9 @@ async def _ensure_sync_result(result: _RT, calling_method: Any) -> _RT: return result if not is_cursor: - cursor_result = getattr(result, "raw", None) # type: ignore + cursor_result = getattr(result, "raw", None) # type: ignore[assignment] # noqa: E501 else: - cursor_result = result # type: ignore + cursor_result = result # type: ignore[assignment] if cursor_result and cursor_result.context._is_server_side: await greenlet_spawn(cursor_result.close) raise async_exc.AsyncMethodRequired( diff --git a/lib/sqlalchemy/ext/asyncio/session.py b/lib/sqlalchemy/ext/asyncio/session.py index b91a4729b9..fc040625e8 100644 --- a/lib/sqlalchemy/ext/asyncio/session.py +++ b/lib/sqlalchemy/ext/asyncio/session.py @@ -1757,7 +1757,7 @@ class async_sessionmaker(Generic[_AS]): self, bind: Optional[_AsyncSessionBind] = None, *, - class_: Type[_AS] = AsyncSession, # type: ignore + class_: Type[_AS] = AsyncSession, # type: ignore[assignment] autoflush: bool = True, expire_on_commit: bool = True, info: Optional[_InfoType] = None, @@ -2003,4 +2003,4 @@ async def close_all_sessions() -> None: await greenlet_spawn(_sync_close_all_sessions) -_instance_state._async_provider = async_session # type: ignore +_instance_state._async_provider = async_session # type: ignore[attr-defined] diff --git a/lib/sqlalchemy/ext/hybrid.py b/lib/sqlalchemy/ext/hybrid.py index f0efee6b76..e4c8a7d292 100644 --- a/lib/sqlalchemy/ext/hybrid.py +++ b/lib/sqlalchemy/ext/hybrid.py @@ -1330,7 +1330,7 @@ class hybrid_method(interfaces.InspectionAttrInfo, Generic[_P, _R]): if expr is not None: self.expression(expr) else: - self.expression(func) # type: ignore + self.expression(func) # type: ignore[arg-type] @property def inplace(self) -> Self: @@ -1363,9 +1363,9 @@ class hybrid_method(interfaces.InspectionAttrInfo, Generic[_P, _R]): self, instance: Optional[object], owner: Type[object] ) -> Union[Callable[_P, _R], Callable[_P, SQLCoreOperations[_R]]]: if instance is None: - return self.expr.__get__(owner, owner) # type: ignore + return self.expr.__get__(owner, owner) # type: ignore[no-any-return] # noqa: E501 else: - return self.func.__get__(instance, owner) # type: ignore + return self.func.__get__(instance, owner) # type: ignore[no-any-return] # noqa: E501 def expression( self, expr: Callable[Concatenate[Any, _P], SQLCoreOperations[_R]] @@ -1381,7 +1381,7 @@ class hybrid_method(interfaces.InspectionAttrInfo, Generic[_P, _R]): def _unwrap_classmethod(meth: _T) -> _T: if isinstance(meth, classmethod): - return meth.__func__ # type: ignore + return meth.__func__ # type: ignore[return-value] else: return meth @@ -1864,7 +1864,7 @@ class ExprComparator(Comparator[_T]): # this accessor is not normally used, however is accessed by things # like ORM synonyms if the hybrid is used in this context; the # .property attribute is not necessarily accessible - return self.expression.property # type: ignore + return self.expression.property # type: ignore[no-any-return, union-attr] # noqa: E501 def operate( self, op: OperatorType, *other: Any, **kwargs: Any @@ -1874,4 +1874,4 @@ class ExprComparator(Comparator[_T]): def reverse_operate( self, op: OperatorType, other: Any, **kwargs: Any ) -> ColumnElement[Any]: - return op(other, self.expression, **kwargs) # type: ignore + return op(other, self.expression, **kwargs) # type: ignore[no-any-return] # noqa: E501 diff --git a/lib/sqlalchemy/log.py b/lib/sqlalchemy/log.py index 7250d73ba5..c72f156ed2 100644 --- a/lib/sqlalchemy/log.py +++ b/lib/sqlalchemy/log.py @@ -233,7 +233,7 @@ def instance_logger( else: name = _qual_logger_name_for_cls(instance.__class__) - instance._echo = echoflag # type: ignore + instance._echo = echoflag # type: ignore[misc] logger: Union[logging.Logger, InstanceLogger] @@ -247,7 +247,7 @@ def instance_logger( # levels by calling logger._log() logger = InstanceLogger(echoflag, name) - instance.logger = logger # type: ignore + instance.logger = logger # type: ignore[misc] class echo_property: diff --git a/lib/sqlalchemy/orm/_typing.py b/lib/sqlalchemy/orm/_typing.py index 2c9953345a..d224b169ed 100644 --- a/lib/sqlalchemy/orm/_typing.py +++ b/lib/sqlalchemy/orm/_typing.py @@ -127,7 +127,7 @@ def is_orm_option( def is_user_defined_option( opt: ExecutableOption, ) -> TypeGuard[UserDefinedOption]: - return not opt._is_core and opt._is_user_defined # type: ignore + return not opt._is_core and opt._is_user_defined # type: ignore[attr-defined] # noqa: E501 def is_composite_class(obj: Any) -> bool: diff --git a/lib/sqlalchemy/orm/attributes.py b/lib/sqlalchemy/orm/attributes.py index 97c8eb72a4..47450956e8 100644 --- a/lib/sqlalchemy/orm/attributes.py +++ b/lib/sqlalchemy/orm/attributes.py @@ -214,7 +214,7 @@ class QueryableAttribute( # interim class manager setup, there's a check for None to see if it # needs to be populated, so we assign None here leaving the attribute # in a temporarily not-type-correct state - self.impl = impl # type: ignore + self.impl = impl # type: ignore[assignment] assert comparator is not None self.comparator = comparator @@ -231,7 +231,7 @@ class QueryableAttribute( if key in base: self.dispatch._update(base[key].dispatch) if base[key].dispatch._active_history: - self.dispatch._active_history = True # type: ignore + self.dispatch._active_history = True # type: ignore[attr-defined] # noqa: E501 _cache_key_traversal = [ ("key", visitors.ExtendedInternalTraversal.dp_string), @@ -534,11 +534,11 @@ class InstrumentedAttribute(QueryableAttribute[_T_co]): def __doc__(self) -> Optional[str]: return self._doc - @__doc__.setter # type: ignore + @__doc__.setter # type: ignore[no-redef] def __doc__(self, value: Optional[str]) -> None: self._doc = value - @__doc__.classlevel # type: ignore + @__doc__.classlevel # type: ignore[no-redef] def __doc__(cls) -> Optional[str]: return super().__doc__ @@ -2684,7 +2684,7 @@ def _register_descriptor( class_, key, comparator=comparator, parententity=parententity ) - descriptor.__doc__ = doc # type: ignore + descriptor.__doc__ = doc # type: ignore[method-assign] manager.instrument_attribute(key, descriptor) return descriptor diff --git a/lib/sqlalchemy/orm/base.py b/lib/sqlalchemy/orm/base.py index 8a26e2686f..94a21c13dc 100644 --- a/lib/sqlalchemy/orm/base.py +++ b/lib/sqlalchemy/orm/base.py @@ -457,7 +457,7 @@ def _class_to_mapper( # can't get mypy to see an overload for this insp = inspection.inspect(class_or_mapper, False) if insp is not None: - return insp.mapper # type: ignore + return insp.mapper # type: ignore[no-any-return] else: assert isinstance(class_or_mapper, type) raise exc.UnmappedClassError(class_or_mapper) @@ -473,7 +473,7 @@ def _mapper_or_none( # can't get mypy to see an overload for this insp = inspection.inspect(entity, False) if insp is not None: - return insp.mapper # type: ignore + return insp.mapper # type: ignore[no-any-return] else: return None diff --git a/lib/sqlalchemy/orm/clsregistry.py b/lib/sqlalchemy/orm/clsregistry.py index 49d20f852c..3c35763b80 100644 --- a/lib/sqlalchemy/orm/clsregistry.py +++ b/lib/sqlalchemy/orm/clsregistry.py @@ -599,7 +599,7 @@ class _class_resolver: self._raise_for_name(n.args[0], n) -_fallback_dict: Mapping[str, Any] = None # type: ignore +_fallback_dict: Mapping[str, Any] = None # type: ignore[assignment] def _resolver(cls: Type[Any], prop: RelationshipProperty[Any]) -> Tuple[ diff --git a/lib/sqlalchemy/orm/collections.py b/lib/sqlalchemy/orm/collections.py index 19eb3ddbfc..aa417f8b2f 100644 --- a/lib/sqlalchemy/orm/collections.py +++ b/lib/sqlalchemy/orm/collections.py @@ -466,7 +466,7 @@ class CollectionAdapter: # is realistically only during garbage collection of this object, so # we type this as a callable that returns _AdaptedCollectionProtocol # in all cases. - self._data = weakref.ref(data) # type: ignore + self._data = weakref.ref(data) # type: ignore[assignment] self.owner_state = owner_state data._sa_adapter = self @@ -725,7 +725,7 @@ class CollectionAdapter: self.owner_state = d["owner_state"] # see note in constructor regarding this type: ignore - self._data = weakref.ref(d["data"]) # type: ignore + self._data = weakref.ref(d["data"]) # type: ignore[assignment] d["data"]._sa_adapter = self self.invalidated = d["invalidated"] diff --git a/lib/sqlalchemy/orm/decl_api.py b/lib/sqlalchemy/orm/decl_api.py index 505df8cfbe..df1a42601d 100644 --- a/lib/sqlalchemy/orm/decl_api.py +++ b/lib/sqlalchemy/orm/decl_api.py @@ -459,7 +459,7 @@ class declared_attr(interfaces._MappedAttribute[_T_co], _declared_attr_common): @hybridproperty def directive(cls) -> _declared_directive[Any]: # see mapping_api.rst for docstring - return _declared_directive # type: ignore + return _declared_directive # type: ignore[return-value] @hybridproperty def cascading(cls) -> _stateful_declared_attr[_T_co]: @@ -594,7 +594,7 @@ def _generate_dc_transforms( _DeclarativeMapperConfig._assert_dc_arguments(current) - cls_._sa_apply_dc_transforms = { # type: ignore # noqa: E501 + cls_._sa_apply_dc_transforms = { # type: ignore[attr-defined] # noqa: E501 k: current.get(k, _NoArg.NO_ARG) if v is _NoArg.NO_ARG else v for k, v in apply_dc_transforms.items() } @@ -1373,7 +1373,7 @@ class registry(EventTarget): # we search through full __mro__ for types. however... sql_type = self.type_annotation_map.get(pt) if sql_type is None: - sql_type = sqltypes._type_map_get(pt) # type: ignore # noqa: E501 + sql_type = sqltypes._type_map_get(pt) # type: ignore[arg-type] # noqa: E501 if sql_type is not None: sql_type_inst = sqltypes.to_instance(sql_type) @@ -1812,7 +1812,7 @@ class registry(EventTarget): def decorate(cls: Type[_T]) -> Type[_T]: kw["cls"] = cls kw["name"] = cls.__name__ - return self.generate_base(**kw) # type: ignore + return self.generate_base(**kw) # type: ignore[no-any-return] return decorate @@ -1864,7 +1864,7 @@ class registry(EventTarget): """ _ORMClassConfigurator._as_declarative(self, cls, cls.__dict__) - return cls.__mapper__ # type: ignore + return cls.__mapper__ # type: ignore[attr-defined, no-any-return] def map_imperatively( self, diff --git a/lib/sqlalchemy/orm/decl_base.py b/lib/sqlalchemy/orm/decl_base.py index 46d7786aec..ed491a18b2 100644 --- a/lib/sqlalchemy/orm/decl_base.py +++ b/lib/sqlalchemy/orm/decl_base.py @@ -1562,7 +1562,7 @@ class _DeclarativeMapperConfig(_MapperConfig, _ClassScanAbstractConfig): continue elif isinstance(value, Column): _undefer_column_name( - k, self.column_copies.get(value, value) # type: ignore + k, self.column_copies.get(value, value) # type: ignore[arg-type] # noqa: E501 ) else: if isinstance(value, _IntrospectsAnnotations): @@ -1756,7 +1756,7 @@ class _DeclarativeMapperConfig(_MapperConfig, _ClassScanAbstractConfig): if hasattr(cls, "__table_cls__"): table_cls = cast( Type[Table], - util.unbound_method_to_callable(cls.__table_cls__), # type: ignore # noqa: E501 + util.unbound_method_to_callable(cls.__table_cls__), # type: ignore[no-untyped-call] # noqa: E501 ) else: table_cls = Table @@ -2009,7 +2009,7 @@ class _DeclarativeMapperConfig(_MapperConfig, _ClassScanAbstractConfig): mapper_cls = cast( "Type[Mapper[Any]]", util.unbound_method_to_callable( - self.cls.__mapper_cls__ # type: ignore + self.cls.__mapper_cls__ # type: ignore[no-untyped-call] ), ) else: @@ -2137,7 +2137,7 @@ class _DeferredDeclarativeConfig(_DeclarativeMapperConfig): @property def cls(self) -> Type[Any]: - return self._cls() # type: ignore + return self._cls() # type: ignore[return-value] @cls.setter def cls(self, class_: Type[Any]) -> None: diff --git a/lib/sqlalchemy/orm/descriptor_props.py b/lib/sqlalchemy/orm/descriptor_props.py index 47b0469884..f25c607092 100644 --- a/lib/sqlalchemy/orm/descriptor_props.py +++ b/lib/sqlalchemy/orm/descriptor_props.py @@ -129,7 +129,7 @@ class DescriptorProperty(MapperProperty[_T]): collection = False @property - def uses_objects(self) -> bool: # type: ignore + def uses_objects(self) -> bool: # type: ignore[override] return prop.uses_objects def __init__(self, key: str): @@ -237,9 +237,9 @@ class CompositeProperty( if isinstance(_class_or_attr, (Mapped, str, sql.ColumnElement)): self.attrs = (_class_or_attr,) + attrs # will initialize within declarative_scan - self.composite_class = None # type: ignore + self.composite_class = None # type: ignore[assignment] else: - self.composite_class = _class_or_attr # type: ignore + self.composite_class = _class_or_attr # type: ignore[assignment] self.attrs = attrs self.return_none_on = return_none_on @@ -291,7 +291,7 @@ class CompositeProperty( " method; can't get state" ) from ae else: - return accessor() # type: ignore + return accessor() # type: ignore[no-any-return] def do_init(self) -> None: """Initialization which occurs after the :class:`.Composite` @@ -671,7 +671,7 @@ class CompositeProperty( ) proxy_attr = self.parent.class_manager[self.key] - proxy_attr.impl.dispatch = proxy_attr.dispatch # type: ignore + proxy_attr.impl.dispatch = proxy_attr.dispatch # type: ignore[assignment] # noqa: E501 proxy_attr.impl.dispatch._active_history = self.active_history # TODO: need a deserialize hook here @@ -688,7 +688,7 @@ class CompositeProperty( else: def get_values(val: Any) -> Tuple[Any]: - return val.__composite_values__() # type: ignore + return val.__composite_values__() # type: ignore[no-any-return] # noqa: E501 attrs = [prop.key for prop in self.props] @@ -790,7 +790,7 @@ class CompositeProperty( """ # https://github.com/python/mypy/issues/4266 - __hash__ = None # type: ignore + __hash__ = None # type: ignore[assignment] prop: RODescriptorReference[Composite[_PT]] @@ -964,7 +964,7 @@ class ConcreteInheritedProperty(DescriptorProperty[_T]): comparator_callable = p.comparator_factory break assert comparator_callable is not None - return comparator_callable(p, mapper) # type: ignore + return comparator_callable(p, mapper) # type: ignore[no-any-return] def __init__(self) -> None: super().__init__() diff --git a/lib/sqlalchemy/orm/exc.py b/lib/sqlalchemy/orm/exc.py index fec401b740..02a0f47f01 100644 --- a/lib/sqlalchemy/orm/exc.py +++ b/lib/sqlalchemy/orm/exc.py @@ -223,7 +223,7 @@ def _default_unmapped(cls: Type[Any]) -> Optional[str]: base = util.preloaded.orm_base try: - mappers = base.manager_of_class(cls).mappers # type: ignore + mappers = base.manager_of_class(cls).mappers # type: ignore[attr-defined] # noqa: E501 except ( UnmappedClassError, TypeError, diff --git a/lib/sqlalchemy/orm/identity.py b/lib/sqlalchemy/orm/identity.py index e4428801ac..243de427d6 100644 --- a/lib/sqlalchemy/orm/identity.py +++ b/lib/sqlalchemy/orm/identity.py @@ -46,7 +46,7 @@ class IdentityMap: self._wr = weakref.ref(self) def _kill(self) -> None: - self._add_unpresent = _killed # type: ignore + self._add_unpresent = _killed # type: ignore[method-assign] def all_states(self) -> List[InstanceState[Any]]: raise NotImplementedError() diff --git a/lib/sqlalchemy/orm/instrumentation.py b/lib/sqlalchemy/orm/instrumentation.py index e32bfa4914..006c22a42d 100644 --- a/lib/sqlalchemy/orm/instrumentation.py +++ b/lib/sqlalchemy/orm/instrumentation.py @@ -418,7 +418,7 @@ class ClassManager( self.uninstall_member(key) self.mapper = None - self.dispatch = None # type: ignore + self.dispatch = None # type: ignore[assignment] self.new_init = None self.info.clear() diff --git a/lib/sqlalchemy/orm/interfaces.py b/lib/sqlalchemy/orm/interfaces.py index 5f638386cd..74a4a12e8d 100644 --- a/lib/sqlalchemy/orm/interfaces.py +++ b/lib/sqlalchemy/orm/interfaces.py @@ -709,7 +709,7 @@ class MapperProperty( """ - return getattr(self.parent.class_, self.key) # type: ignore + return getattr(self.parent.class_, self.key) # type: ignore[no-any-return] # noqa: E501 def do_init(self) -> None: """Perform subclass-specific initialization post-mapper-creation @@ -1004,7 +1004,7 @@ class PropComparator(SQLORMOperations[_T_co], Generic[_T_co], ColumnOperators): """ - return self.operate(PropComparator.of_type_op, class_) # type: ignore + return self.operate(PropComparator.of_type_op, class_) # type: ignore[return-value] # noqa: E501 def and_( self, *criteria: _ColumnExpressionArgument[bool] @@ -1034,7 +1034,7 @@ class PropComparator(SQLORMOperations[_T_co], Generic[_T_co], ColumnOperators): :func:`.with_loader_criteria` """ - return self.operate(operators.and_, *criteria) # type: ignore + return self.operate(operators.and_, *criteria) # type: ignore[return-value] # noqa: E501 def any( self, diff --git a/lib/sqlalchemy/orm/mapped_collection.py b/lib/sqlalchemy/orm/mapped_collection.py index 46c19dc32a..48b66d15a4 100644 --- a/lib/sqlalchemy/orm/mapped_collection.py +++ b/lib/sqlalchemy/orm/mapped_collection.py @@ -125,7 +125,7 @@ class _SerializableColumnGetterV2(_PlainColumnGetter[_KT]): if not isinstance(c.table, expression.TableClause): return None else: - return c.table.key # type: ignore + return c.table.key # type: ignore[attr-defined, no-any-return] colkeys = [(c.key, _table_key(c)) for c in cols] return _SerializableColumnGetterV2, (colkeys,) @@ -135,7 +135,7 @@ class _SerializableColumnGetterV2(_PlainColumnGetter[_KT]): metadata = getattr(mapper.local_table, "metadata", None) for ckey, tkey in self.colkeys: if tkey is None or metadata is None or tkey not in metadata: - cols.append(mapper.local_table.c[ckey]) # type: ignore + cols.append(mapper.local_table.c[ckey]) # type: ignore[index] else: cols.append(metadata.tables[tkey].c[ckey]) return cols diff --git a/lib/sqlalchemy/orm/mapper.py b/lib/sqlalchemy/orm/mapper.py index 58842eee05..6751c719e7 100644 --- a/lib/sqlalchemy/orm/mapper.py +++ b/lib/sqlalchemy/orm/mapper.py @@ -778,7 +778,7 @@ class Mapper( # interim - polymorphic_on is further refined in # _configure_polymorphic_setter self.polymorphic_on = ( - coercions.expect( # type: ignore + coercions.expect( # type: ignore[assignment] roles.ColumnArgumentOrKeyRole, polymorphic_on, argname="polymorphic_on", @@ -1528,12 +1528,12 @@ class Mapper( if fc.primary_key and pk_cols.issuperset(fc.primary_key): # ordering is important since it determines the ordering of # mapper.primary_key (and therefore query.get()) - self._pks_by_table[fc] = util.ordered_column_set( # type: ignore # noqa: E501 + self._pks_by_table[fc] = util.ordered_column_set( # type: ignore[assignment] # noqa: E501 fc.primary_key ).intersection( pk_cols ) - self._cols_by_table[fc] = util.ordered_column_set(fc.c).intersection( # type: ignore # noqa: E501 + self._cols_by_table[fc] = util.ordered_column_set(fc.c).intersection( # type: ignore[assignment] # noqa: E501 all_cols ) @@ -2287,7 +2287,7 @@ class Mapper( "in properties.ColumnProperty %s", key, ) - return new_prop # type: ignore + return new_prop # type: ignore[no-any-return] @util.preload_module("sqlalchemy.orm.descriptor_props") def _property_from_column( @@ -4210,7 +4210,7 @@ def _configure_registries( else: return - Mapper.dispatch._for_class(Mapper).before_configured() # type: ignore # noqa: E501 + Mapper.dispatch._for_class(Mapper).before_configured() # type: ignore[arg-type, call-arg, misc] # noqa: E501 # initialize properties on all mappers # note that _mapper_registry is unordered, which @@ -4225,7 +4225,7 @@ def _configure_registries( _already_compiling = False for reg in registries_configured: reg.dispatch.after_configured(reg) - Mapper.dispatch._for_class(Mapper).after_configured() # type: ignore + Mapper.dispatch._for_class(Mapper).after_configured() # type: ignore[arg-type, call-arg, misc] # noqa: E501 @util.preload_module("sqlalchemy.orm.decl_api") @@ -4261,7 +4261,7 @@ def _do_configure_registries( "Original exception was: %s" % (mapper, mapper._configure_failed) ) - e._configure_failed = mapper._configure_failed # type: ignore + e._configure_failed = mapper._configure_failed # type: ignore[attr-defined] # noqa: E501 raise e if not mapper.configured: diff --git a/lib/sqlalchemy/orm/path_registry.py b/lib/sqlalchemy/orm/path_registry.py index 8e30962d94..9a57939db5 100644 --- a/lib/sqlalchemy/orm/path_registry.py +++ b/lib/sqlalchemy/orm/path_registry.py @@ -158,7 +158,7 @@ class PathRegistry(HasCacheKey): return self.path def odd_element(self, index: int) -> _InternalEntityType[Any]: - return self.path[index] # type: ignore + return self.path[index] # type: ignore[return-value] def set(self, attributes: Dict[Any, Any], key: Any, value: Any) -> None: log.debug("set '%s' on path '%s' to '%s'", key, self, value) @@ -339,7 +339,7 @@ class PathRegistry(HasCacheKey): return prev[next_] # can't quite get mypy to appreciate this one :) - return reduce(_red, raw, cls.root) # type: ignore + return reduce(_red, raw, cls.root) # type: ignore[arg-type] def __add__(self, other: PathRegistry) -> PathRegistry: def _red(prev: PathRegistry, next_: _PathElementType) -> PathRegistry: @@ -427,7 +427,7 @@ class RootRegistry(_CreatesToken): return _TokenRegistry(self, PathToken._intern[entity]) else: try: - return entity._path_registry # type: ignore + return entity._path_registry # type: ignore[no-any-return] except AttributeError: raise IndexError( f"invalid argument for RootRegistry.__getitem__: {entity}" @@ -590,14 +590,14 @@ class _PropRegistry(PathRegistry): parent.mapper.inherits ) - if not insp.is_aliased_class or insp._use_mapper_path: # type: ignore + if not insp.is_aliased_class or insp._use_mapper_path: # type: ignore[union-attr] # noqa: E501 parent = natural_parent = parent.parent[prop.parent] elif ( insp.is_aliased_class and insp.with_polymorphic_mappers and prop.parent in insp.with_polymorphic_mappers ): - subclass_entity: _InternalEntityType[Any] = parent[-1]._entity_for_mapper(prop.parent) # type: ignore # noqa: E501 + subclass_entity: _InternalEntityType[Any] = parent[-1]._entity_for_mapper(prop.parent) # type: ignore[union-attr] # noqa: E501 parent = parent.parent[subclass_entity] # when building a path where with_polymorphic() is in use, @@ -675,7 +675,7 @@ class _PropRegistry(PathRegistry): if earliest is None: return self else: - return self.coerce(self.path[0 : -(earliest + 1)]) # type: ignore + return self.coerce(self.path[0 : -(earliest + 1)]) # type: ignore[return-value] # noqa: E501 @property def entity_path(self) -> _AbstractEntityRegistry: @@ -746,8 +746,8 @@ class _AbstractEntityRegistry(_CreatesToken): parent_natural_entity = parent.natural_path[-1] if entity.mapper.isa( - parent_natural_entity.mapper # type: ignore - ) or parent_natural_entity.mapper.isa( # type: ignore + parent_natural_entity.mapper # type: ignore[union-attr] + ) or parent_natural_entity.mapper.isa( # type: ignore[union-attr] entity.mapper ): # when the entity mapper and parent mapper are in an @@ -761,7 +761,7 @@ class _AbstractEntityRegistry(_CreatesToken): self.natural_path = parent.natural_path + (entity.mapper,) else: self.natural_path = parent.natural_path + ( - parent_natural_entity.entity, # type: ignore + parent_natural_entity.entity, # type: ignore[operator, union-attr] # noqa: E501 ) # it seems to make sense that since these paths get mixed up # with statements that are cached or not, we should make diff --git a/lib/sqlalchemy/orm/properties.py b/lib/sqlalchemy/orm/properties.py index e6314b5b3d..e260a1b50b 100644 --- a/lib/sqlalchemy/orm/properties.py +++ b/lib/sqlalchemy/orm/properties.py @@ -232,14 +232,14 @@ class ColumnProperty( def columns_to_assign(self) -> List[Tuple[Column[Any], int]]: # mypy doesn't care about the isinstance here return [ - (c, 0) # type: ignore + (c, 0) # type: ignore[misc] for c in self.columns if isinstance(c, Column) and c.table is None ] def _memoized_attr__renders_in_subqueries(self) -> bool: if ("query_expression", True) in self.strategy_key: - return self.strategy._have_default_expression # type: ignore + return self.strategy._have_default_expression # type: ignore[attr-defined, no-any-return] # noqa: E501 return ("deferred", True) not in self.strategy_key or ( self not in self.parent._readonly_props @@ -452,7 +452,7 @@ class ColumnProperty( ce = self.__clause_element__() try: - return ce.info # type: ignore + return ce.info # type: ignore[no-any-return] except AttributeError: return self.prop.info diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py index 613625400c..227b0b21e0 100644 --- a/lib/sqlalchemy/orm/query.py +++ b/lib/sqlalchemy/orm/query.py @@ -281,7 +281,7 @@ class Query( # for the query(Entity).with_session(session) API which is likely in # some old recipes, however these are legacy as select() can now be # used. - self.session = session # type: ignore + self.session = session # type: ignore[assignment] self._set_entities(entities) def _set_propagate_attrs(self, values: Mapping[str, Any]) -> Self: @@ -336,7 +336,7 @@ class Query( :meth:`.Result.tuples` - v2 equivalent method. """ - return self.only_return_tuples(True) # type: ignore + return self.only_return_tuples(True) # type: ignore[return-value] def _entity_from_pre_ent_zero(self) -> Optional[_InternalEntityType[Any]]: if not self._raw_columns: @@ -345,14 +345,14 @@ class Query( ent = self._raw_columns[0] if "parententity" in ent._annotations: - return ent._annotations["parententity"] # type: ignore + return ent._annotations["parententity"] # type: ignore[no-any-return] # noqa: E501 elif "bundle" in ent._annotations: - return ent._annotations["bundle"] # type: ignore + return ent._annotations["bundle"] # type: ignore[no-any-return] else: # label, other SQL expression for element in visitors.iterate(ent): if "parententity" in element._annotations: - return element._annotations["parententity"] # type: ignore # noqa: E501 + return element._annotations["parententity"] # type: ignore[no-any-return] # noqa: E501 else: return None @@ -367,7 +367,7 @@ class Query( "a single mapped class." % methname ) - return self._raw_columns[0]._annotations["parententity"] # type: ignore # noqa: E501 + return self._raw_columns[0]._annotations["parententity"] # type: ignore[no-any-return] # noqa: E501 def _set_select_from( self, obj: Iterable[_FromClauseArgument], set_base_alias: bool @@ -569,7 +569,7 @@ class Query( return q._compile_state( use_legacy_query_style=legacy_query_style - ).statement # type: ignore + ).statement # type: ignore[return-value] def _statement_20( self, for_statement: bool = False, use_legacy_query_style: bool = True @@ -582,7 +582,7 @@ class Query( new_query = fn(self) if new_query is not None and new_query is not self: self = new_query - if not fn._bake_ok: # type: ignore + if not fn._bake_ok: # type: ignore[attr-defined] self._compile_options += {"_bake_ok": False} compile_options = self._compile_options @@ -1171,11 +1171,11 @@ class Query( :attr:`.ORMExecuteState.lazy_loaded_from` """ - return self.load_options._lazy_loaded_from # type: ignore + return self.load_options._lazy_loaded_from # type: ignore[no-any-return] # noqa: E501 @property def _current_path(self) -> PathRegistry: - return self._compile_options._current_path # type: ignore + return self._compile_options._current_path # type: ignore[no-any-return] # noqa: E501 @_generative def correlate( @@ -1307,16 +1307,16 @@ class Query( for prop in mapper.iterate_properties: if ( isinstance(prop, relationships.RelationshipProperty) - and prop.mapper is entity_zero.mapper # type: ignore + and prop.mapper is entity_zero.mapper # type: ignore[union-attr] # noqa: E501 ): - property = prop # type: ignore # noqa: A001 + property = prop # type: ignore[assignment] # noqa: A001 break else: raise sa_exc.InvalidRequestError( "Could not locate a property which relates instances " "of class '%s' to instances of class '%s'" % ( - entity_zero.mapper.class_.__name__, # type: ignore + entity_zero.mapper.class_.__name__, # type: ignore[union-attr] # noqa: E501 instance.__class__.__name__, ) ) @@ -1324,8 +1324,8 @@ class Query( return self.filter( with_parent( instance, - property, # type: ignore - entity_zero.entity, # type: ignore + property, # type: ignore[arg-type] + entity_zero.entity, # type: ignore[union-attr] ) ) @@ -1474,7 +1474,7 @@ class Query( """ try: - return next(self._values_no_warn(column))[0] # type: ignore + return next(self._values_no_warn(column))[0] # type: ignore[arg-type, call-overload] # noqa: E501 except StopIteration: return None @@ -1611,7 +1611,7 @@ class Query( # Query has all the same fields as Select for this operation # this could in theory be based on a protocol but not sure if it's # worth it - _MemoizedSelectEntities._generate_for_statement(self) # type: ignore + _MemoizedSelectEntities._generate_for_statement(self) # type: ignore[arg-type] # noqa: E501 self._set_entities(entities) return self @@ -1674,12 +1674,12 @@ class Query( if self._compile_options._current_path: # opting for lower method overhead for the checks for opt in opts: - if not opt._is_core and opt._is_legacy_option: # type: ignore - opt.process_query_conditionally(self) # type: ignore + if not opt._is_core and opt._is_legacy_option: # type: ignore[attr-defined] # noqa: E501 + opt.process_query_conditionally(self) # type: ignore[attr-defined] # noqa: E501 else: for opt in opts: - if not opt._is_core and opt._is_legacy_option: # type: ignore - opt.process_query(self) # type: ignore + if not opt._is_core and opt._is_legacy_option: # type: ignore[attr-defined] # noqa: E501 + opt.process_query(self) # type: ignore[attr-defined] self._with_options += opts return self @@ -2765,7 +2765,7 @@ class Query( :meth:`_engine.Result.scalars` - v2 comparable method. """ - return self._iter().all() # type: ignore + return self._iter().all() # type: ignore[return-value] @_generative @_assertions(_no_clauseelement_condition) @@ -2818,9 +2818,9 @@ class Query( """ # replicates limit(1) behavior if self._statement is not None: - return self._iter().first() # type: ignore + return self._iter().first() # type: ignore[return-value] else: - return self.limit(1)._iter().first() # type: ignore + return self.limit(1)._iter().first() # type: ignore[return-value] def one_or_none(self) -> Optional[_T]: """Return at most one result or raise an exception. @@ -2846,7 +2846,7 @@ class Query( :meth:`_engine.Result.scalar_one_or_none` - v2 comparable method. """ - return self._iter().one_or_none() # type: ignore + return self._iter().one_or_none() # type: ignore[return-value] def one(self) -> _T: """Return exactly one result or raise an exception. @@ -2869,7 +2869,7 @@ class Query( :meth:`_engine.Result.scalar_one` - v2 comparable method. """ - return self._iter().one() # type: ignore + return self._iter().one() # type: ignore[return-value] def scalar(self) -> Any: """Return the first element of the first result or None @@ -2906,7 +2906,7 @@ class Query( def __iter__(self) -> Iterator[_T]: result = self._iter() try: - yield from result # type: ignore + yield from result # type: ignore[misc] except GeneratorExit: # issue #8710 - direct iteration is not reusable after # an iterable block is broken, so close the result @@ -3040,7 +3040,7 @@ class Query( # legacy: automatically set scalars, unique if result._attributes.get("is_single_entity", False): - result = result.scalars() # type: ignore + result = result.scalars() # type: ignore[assignment] if result._attributes.get("filtered", False): result = result.unique() @@ -3203,7 +3203,7 @@ class Query( """ col = sql.func.count(sql.literal_column("*")) - return ( # type: ignore + return ( # type: ignore[no-any-return] self._legacy_from_self(col).enable_eagerloads(False).scalar() ) @@ -3260,7 +3260,7 @@ class Query( self = bulk_del.query - delete_ = sql.delete(*self._raw_columns) # type: ignore + delete_ = sql.delete(*self._raw_columns) # type: ignore[arg-type] if delete_args: delete_ = delete_.with_dialect_options(**delete_args) @@ -3280,7 +3280,7 @@ class Query( ), ), ) - bulk_del.result = result # type: ignore + bulk_del.result = result # type: ignore[attr-defined] self.session.dispatch.after_bulk_delete(bulk_del) result.close() @@ -3353,11 +3353,11 @@ class Query( bulk_ud.query = new_query self = bulk_ud.query - upd = sql.update(*self._raw_columns) # type: ignore + upd = sql.update(*self._raw_columns) # type: ignore[arg-type] ppo = update_args.pop("preserve_parameter_order", False) if ppo: - upd = upd.ordered_values(*values) # type: ignore + upd = upd.ordered_values(*values) # type: ignore[arg-type] else: upd = upd.values(values) if update_args: @@ -3378,7 +3378,7 @@ class Query( ), ), ) - bulk_ud.result = result # type: ignore + bulk_ud.result = result # type: ignore[attr-defined] self.session.dispatch.after_bulk_update(bulk_ud) result.close() return result.rowcount @@ -3524,5 +3524,5 @@ class BulkDelete(BulkUD): class RowReturningQuery(Query[Row[Unpack[_Ts]]]): if TYPE_CHECKING: - def tuples(self) -> Query[Tuple[Unpack[_Ts]]]: # type: ignore + def tuples(self) -> Query[Tuple[Unpack[_Ts]]]: # type: ignore[override] # noqa: E501 ... diff --git a/lib/sqlalchemy/orm/relationships.py b/lib/sqlalchemy/orm/relationships.py index d81ae32ba5..dc903f6962 100644 --- a/lib/sqlalchemy/orm/relationships.py +++ b/lib/sqlalchemy/orm/relationships.py @@ -230,7 +230,7 @@ def remote(expr: _CEA) -> _CEA: :func:`.foreign` """ - return _annotate_columns( # type: ignore + return _annotate_columns( # type: ignore[return-value] coercions.expect(roles.ColumnArgumentRole, expr), {"remote": True} ) @@ -250,7 +250,7 @@ def foreign(expr: _CEA) -> _CEA: """ - return _annotate_columns( # type: ignore + return _annotate_columns( # type: ignore[return-value] coercions.expect(roles.ColumnArgumentRole, expr), {"foreign": True} ) @@ -305,7 +305,7 @@ class _StringRelationshipArg(_RelationshipArg[_T1, _T2]): attr_value = attr_value() if isinstance(attr_value, attributes.QueryableAttribute): - attr_value = attr_value.key # type: ignore + attr_value = attr_value.key # type: ignore[assignment] self.resolved = attr_value @@ -530,7 +530,7 @@ class RelationshipProperty( self._reverse_property: Set[RelationshipProperty[Any]] = set() if overlaps: - self._overlaps = set(re.split(r"\s*,\s*", overlaps)) # type: ignore # noqa: E501 + self._overlaps = set(re.split(r"\s*,\s*", overlaps)) # type: ignore[assignment] # noqa: E501 else: self._overlaps = () @@ -548,7 +548,7 @@ class RelationshipProperty( @property def back_populates(self) -> str: - return self._init_args.back_populates.effective_value() # type: ignore + return self._init_args.back_populates.effective_value() # type: ignore[no-any-return] # noqa: E501 @back_populates.setter def back_populates(self, value: str) -> None: @@ -667,7 +667,7 @@ class RelationshipProperty( def _memoized_attr_entity(self) -> _InternalEntityType[_PT]: if self._of_type: - return inspect(self._of_type) # type: ignore + return inspect(self._of_type) # type: ignore[return-value] else: return self.prop.entity @@ -757,7 +757,7 @@ class RelationshipProperty( ) # https://github.com/python/mypy/issues/4266 - __hash__ = None # type: ignore + __hash__ = None # type: ignore[assignment] def __eq__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501 """Implement the ``==`` operator. @@ -1868,13 +1868,13 @@ class RelationshipProperty( elif not is_write_only and not is_dynamic: self.uselist = False - if argument.__args__: # type: ignore + if argument.__args__: # type: ignore[union-attr] if isinstance(arg_origin, type) and issubclass( arg_origin, typing.Mapping ): - type_arg = argument.__args__[-1] # type: ignore + type_arg = argument.__args__[-1] # type: ignore[union-attr] # noqa: E501 else: - type_arg = argument.__args__[0] # type: ignore + type_arg = argument.__args__[0] # type: ignore[union-attr] if hasattr(type_arg, "__forward_arg__"): str_argument = type_arg.__forward_arg__ @@ -1958,7 +1958,7 @@ class RelationshipProperty( try: entity = inspect(resolved_argument) except sa_exc.NoInspectionAvailable: - entity = None # type: ignore + entity = None # type: ignore[assignment] if not hasattr(entity, "mapper"): raise sa_exc.ArgumentError( @@ -2220,7 +2220,7 @@ class RelationshipProperty( if self.uselist is None: self.uselist = self.direction is not MANYTOONE if not self.viewonly: - self._dependency_processor = ( # type: ignore + self._dependency_processor = ( # type: ignore[no-untyped-call] dependency._DependencyProcessor.from_relationship )(self) @@ -2335,13 +2335,13 @@ class RelationshipProperty( def _annotate_columns(element: _CE, annotations: _AnnotationDict) -> _CE: def clone(elem: _CE) -> _CE: if isinstance(elem, expression.ColumnClause): - elem = elem._annotate(annotations.copy()) # type: ignore + elem = elem._annotate(annotations.copy()) # type: ignore[attr-defined] # noqa: E501 elem._copy_internals(clone=clone) return elem if element is not None: element = clone(element) - clone = None # type: ignore # remove gc cycles + clone = None # type: ignore[assignment] # remove gc cycles return element diff --git a/lib/sqlalchemy/orm/scoping.py b/lib/sqlalchemy/orm/scoping.py index bbebee5c42..3abbd21f3e 100644 --- a/lib/sqlalchemy/orm/scoping.py +++ b/lib/sqlalchemy/orm/scoping.py @@ -310,7 +310,7 @@ class scoped_session(Generic[_S]): def __get__(s, instance: Any, owner: Type[_O]) -> Query[_O]: if query_cls: # custom query class - return query_cls(owner, session=self.registry()) # type: ignore # noqa: E501 + return query_cls(owner, session=self.registry()) # type: ignore[return-value] # noqa: E501 else: # session's configured query class return self.registry().query(owner) diff --git a/lib/sqlalchemy/orm/session.py b/lib/sqlalchemy/orm/session.py index f5927c4d88..0b3f5785d1 100644 --- a/lib/sqlalchemy/orm/session.py +++ b/lib/sqlalchemy/orm/session.py @@ -667,7 +667,7 @@ class ORMExecuteState(util.MemoizedSlots): if opts is not None and opts.isinstance( context._ORMCompileState.default_compile_options ): - return opts # type: ignore + return opts # type: ignore[return-value] else: return None @@ -1824,7 +1824,7 @@ class Session(_SessionClassMethods, EventTarget): if ( join_transaction_mode and join_transaction_mode - not in JoinTransactionMode.__args__ # type: ignore + not in JoinTransactionMode.__args__ # type: ignore[attr-defined] ): raise sa_exc.ArgumentError( f"invalid selection for join_transaction_mode: " @@ -5219,7 +5219,7 @@ class sessionmaker(_SessionClassMethods, Generic[_S]): self, bind: Optional[_SessionBind] = None, *, - class_: Type[_S] = Session, # type: ignore + class_: Type[_S] = Session, # type: ignore[assignment] autoflush: bool = True, expire_on_commit: bool = True, info: Optional[_InfoType] = None, diff --git a/lib/sqlalchemy/orm/state.py b/lib/sqlalchemy/orm/state.py index 3f1d7fa740..f75e739288 100644 --- a/lib/sqlalchemy/orm/state.py +++ b/lib/sqlalchemy/orm/state.py @@ -535,7 +535,7 @@ class InstanceState(interfaces.InspectionAttrInfo, Generic[_O]): del obj self._cleanup(self.obj) - self.obj = lambda: None # type: ignore + self.obj = lambda: None # type: ignore[assignment] def _cleanup(self, ref: weakref.ref[_O]) -> None: """Weakref callback cleanup. @@ -644,7 +644,7 @@ class InstanceState(interfaces.InspectionAttrInfo, Generic[_O]): self.obj = weakref.ref(inst, self._cleanup) self.class_ = inst.__class__ else: - self.obj = lambda: None # type: ignore + self.obj = lambda: None # type: ignore[assignment] self.class_ = state_dict["class_"] self.committed_state = state_dict.get("committed_state", {}) diff --git a/lib/sqlalchemy/orm/strategy_options.py b/lib/sqlalchemy/orm/strategy_options.py index 7932388239..8afdc6e027 100644 --- a/lib/sqlalchemy/orm/strategy_options.py +++ b/lib/sqlalchemy/orm/strategy_options.py @@ -953,7 +953,7 @@ class _AbstractLoad(traversals.GenerativeOnTraversal, LoaderOption): return to_chop elif ( c_token != f"{_RELATIONSHIP_TOKEN}:{_WILDCARD_TOKEN}" - and c_token != p_token.key # type: ignore + and c_token != p_token.key # type: ignore[union-attr] ): return None @@ -1770,7 +1770,7 @@ class _LoadElement( ) if not path: - return None # type: ignore + return None # type: ignore[return-value] assert opt.is_token_strategy == path.is_token @@ -2402,7 +2402,7 @@ def _parse_attr_argument( # TODO: need to figure out this None thing being returned by # inspect(), it should not have None as an option in most cases # if at all - insp: InspectionAttr = inspect(attr) # type: ignore + insp: InspectionAttr = inspect(attr) # type: ignore[assignment] except sa_exc.NoInspectionAvailable as err: raise sa_exc.ArgumentError( "expected ORM mapped attribute for loader strategy argument" diff --git a/lib/sqlalchemy/orm/util.py b/lib/sqlalchemy/orm/util.py index 2b49563a31..8dfd689230 100644 --- a/lib/sqlalchemy/orm/util.py +++ b/lib/sqlalchemy/orm/util.py @@ -213,7 +213,7 @@ class CascadeOptions(FrozenSet[str]): cls, value_list: Optional[Union[Iterable[str], str]] ) -> CascadeOptions: if isinstance(value_list, str) or value_list is None: - return cls.from_string(value_list) # type: ignore + return cls.from_string(value_list) # type: ignore[no-any-return] values = set(value_list) if values.difference(cls._allowed_cascades): raise sa_exc.ArgumentError( @@ -1152,7 +1152,7 @@ class AliasedInsp( } def __setstate__(self, state: Dict[str, Any]) -> None: - self.__init__( # type: ignore + self.__init__( # type: ignore[misc] state["entity"], state["mapper"], state["alias"], @@ -1499,7 +1499,7 @@ class LoaderCriteriaOption(CriteriaOption): self.where_criteria._resolve_with_args(ext_info.entity), ) else: - crit = self.where_criteria # type: ignore + crit = self.where_criteria # type: ignore[assignment] assert isinstance(crit, ColumnElement) return sql_util._deep_annotate( crit, @@ -1950,7 +1950,7 @@ class _ORMJoin(expression.Join): if ( not prop and getattr(right_info, "mapper", None) - and right_info.mapper.single # type: ignore + and right_info.mapper.single # type: ignore[union-attr] ): right_info = cast("_InternalEntityType[Any]", right_info) # if single inheritance target and we are using a manual @@ -2390,14 +2390,14 @@ def _extract_mapped_subtype( "module level. See chained stack trace for more hints." ) from ce except NameError as ne: - if raiseerr and "Mapped[" in raw_annotation: # type: ignore + if raiseerr and "Mapped[" in raw_annotation: # type: ignore[operator] raise orm_exc.MappedAnnotationError( f"Could not interpret annotation {raw_annotation}. " "Check that it uses names that are correctly imported at the " "module level. See chained stack trace for more hints." ) from ne - annotated = raw_annotation # type: ignore + annotated = raw_annotation # type: ignore[assignment] if is_dataclass_field: return annotated, None diff --git a/lib/sqlalchemy/pool/base.py b/lib/sqlalchemy/pool/base.py index 5ef01568a3..6b08224dca 100644 --- a/lib/sqlalchemy/pool/base.py +++ b/lib/sqlalchemy/pool/base.py @@ -1037,7 +1037,7 @@ def _finalize_fairy( # which actually started failing when pytest warnings plugin was # turned on, due to util.warn() above if fairy is not None: - fairy.dbapi_connection = None # type: ignore + fairy.dbapi_connection = None # type: ignore[assignment] fairy._connection_record = None del dbapi_connection del connection_record @@ -1482,7 +1482,7 @@ class _ConnectionFairy(PoolProxiedConnection): if not soft: # prevent any rollback / reset actions etc. on # the connection - self.dbapi_connection = None # type: ignore + self.dbapi_connection = None # type: ignore[assignment] # finalize self._checkin() @@ -1504,7 +1504,7 @@ class _ConnectionFairy(PoolProxiedConnection): # can't get the descriptor assignment to work here # in pylance. mypy is OK w/ it - self.info = self.info.copy() # type: ignore + self.info = self.info.copy() # type: ignore[misc] self._connection_record = None diff --git a/lib/sqlalchemy/sql/_elements_constructors.py b/lib/sqlalchemy/sql/_elements_constructors.py index 4816d172b9..1273d7c23a 100644 --- a/lib/sqlalchemy/sql/_elements_constructors.py +++ b/lib/sqlalchemy/sql/_elements_constructors.py @@ -385,7 +385,7 @@ def collate( """ if isinstance(expression, operators.ColumnOperators): - return expression.collate(collation) # type: ignore + return expression.collate(collation) # type: ignore[return-value] else: return CollationClause._create_collation_expression( expression, collation diff --git a/lib/sqlalchemy/sql/_typing.py b/lib/sqlalchemy/sql/_typing.py index 492601e554..1a8618b3cf 100644 --- a/lib/sqlalchemy/sql/_typing.py +++ b/lib/sqlalchemy/sql/_typing.py @@ -400,7 +400,7 @@ def is_has_clause_element(s: object) -> TypeGuard[_HasClauseElement[Any]]: def is_insert_update(c: ClauseElement) -> TypeGuard[ValuesBase]: - return c.is_dml and (c.is_insert or c.is_update) # type: ignore + return c.is_dml and (c.is_insert or c.is_update) # type: ignore[attr-defined] # noqa: E501 def _no_kw() -> exc.ArgumentError: @@ -484,4 +484,4 @@ def NotNullable( .. versionadded:: 2.0.20 """ - return val # type: ignore + return val # type: ignore[return-value] diff --git a/lib/sqlalchemy/sql/annotation.py b/lib/sqlalchemy/sql/annotation.py index a66880868f..30d4e2d2d4 100644 --- a/lib/sqlalchemy/sql/annotation.py +++ b/lib/sqlalchemy/sql/annotation.py @@ -129,14 +129,14 @@ class SupportsWrappingAnnotations(SupportsAnnotations): updated by the given dictionary. """ - return Annotated._as_annotated_instance(self, values) # type: ignore + return Annotated._as_annotated_instance(self, values) # type: ignore[return-value] # noqa: E501 def _with_annotations(self, values: _AnnotationDict) -> Self: """return a copy of this ClauseElement with annotations replaced by the given dictionary. """ - return Annotated._as_annotated_instance(self, values) # type: ignore + return Annotated._as_annotated_instance(self, values) # type: ignore[return-value] # noqa: E501 @overload def _deannotate( @@ -478,7 +478,7 @@ def _deep_annotate( if element is not None: element = cast(_SA, clone(element)) - clone = None # type: ignore # remove gc cycles + clone = None # type: ignore[assignment] # remove gc cycles return element @@ -518,7 +518,7 @@ def _deep_deannotate( if element is not None: element = cast(_SA, clone(element)) - clone = None # type: ignore # remove gc cycles + clone = None # type: ignore[assignment] # remove gc cycles return element @@ -573,9 +573,9 @@ def _new_annotation_type( # some classes include this even if they have traverse_internals # e.g. BindParameter, add it if present. if cls.__dict__.get("inherit_cache", False): - anno_cls.inherit_cache = True # type: ignore + anno_cls.inherit_cache = True # type: ignore[attr-defined] elif "inherit_cache" in cls.__dict__: - anno_cls.inherit_cache = cls.__dict__["inherit_cache"] # type: ignore + anno_cls.inherit_cache = cls.__dict__["inherit_cache"] # type: ignore[attr-defined] # noqa: E501 anno_cls._is_column_operators = issubclass(cls, operators.ColumnOperators) diff --git a/lib/sqlalchemy/sql/base.py b/lib/sqlalchemy/sql/base.py index 6f321c2cdd..0fd032c851 100644 --- a/lib/sqlalchemy/sql/base.py +++ b/lib/sqlalchemy/sql/base.py @@ -151,7 +151,7 @@ class _DefaultDescriptionTuple(NamedTuple): ) -> _DefaultDescriptionTuple: return ( _DefaultDescriptionTuple( - default.arg, # type: ignore + default.arg, # type: ignore[attr-defined] default.is_scalar, default.is_callable, default.is_sentinel, @@ -236,7 +236,7 @@ class SingletonConstant(Immutable): @classmethod def _create_singleton(cls) -> None: obj = object.__new__(cls) - obj.__init__() # type: ignore + obj.__init__() # type: ignore[misc] # for a long time this was an empty frozenset, meaning # a SingletonConstant would never be a "corresponding column" in @@ -298,7 +298,7 @@ def _generative(fn: _Fn) -> _Fn: return self decorated = _generative(fn) - decorated.non_generative = fn # type: ignore + decorated.non_generative = fn # type: ignore[attr-defined] return decorated @@ -1103,7 +1103,7 @@ class ExecutableOption(HasCopyInternals): def _clone(self, **kw): """Create a shallow copy of this ExecutableOption.""" c = self.__class__.__new__(self.__class__) - c.__dict__ = dict(self.__dict__) # type: ignore + c.__dict__ = dict(self.__dict__) # type: ignore[misc] return c @@ -2011,7 +2011,7 @@ class ColumnCollection(Generic[_COLKEY, _COL_co]): ) # https://github.com/python/mypy/issues/4266 - __hash__: Optional[int] = None # type: ignore + __hash__: Optional[int] = None # type: ignore[assignment] def contains_column(self, col: ColumnElement[Any]) -> bool: """Checks if a column object exists in this collection""" @@ -2154,7 +2154,7 @@ class WriteableColumnCollection(ColumnCollection[_COLKEY, _COL_co]): colkey: _COLKEY if key is None: - colkey = column.key # type: ignore + colkey = column.key # type: ignore[assignment] else: colkey = key @@ -2545,7 +2545,7 @@ class ReadOnlyColumnCollection( def __setstate__(self, state: Dict[str, Any]) -> None: parent = state["_parent"] - self.__init__(parent) # type: ignore + self.__init__(parent) # type: ignore[misc] def corresponding_column( self, column: _COL, require_embedded: bool = False @@ -2644,7 +2644,7 @@ def _entity_namespace_key( if default is not NO_ARG: return getattr(ns, key, default) else: - return getattr(ns, key) # type: ignore + return getattr(ns, key) # type: ignore[no-any-return] except AttributeError as err: raise exc.InvalidRequestError( 'Entity namespace for "%s" has no property "%s"' % (entity, key) diff --git a/lib/sqlalchemy/sql/cache_key.py b/lib/sqlalchemy/sql/cache_key.py index fbf02f893d..1759cf3b54 100644 --- a/lib/sqlalchemy/sql/cache_key.py +++ b/lib/sqlalchemy/sql/cache_key.py @@ -287,7 +287,7 @@ class HasCacheKey: elif meth is ANON_NAME: elements = util.preloaded.sql_elements if isinstance(obj, elements._anonymous_label): - obj = obj.apply_map(anon_map) # type: ignore + obj = obj.apply_map(anon_map) # type: ignore[arg-type] result += (attrname, obj) elif meth is CALL_GEN_CACHE_KEY: result += ( @@ -320,10 +320,10 @@ class HasCacheKey: # Join, Aliased, etc. # see #8790 - if self._gen_static_annotations_cache_key: # type: ignore # noqa: E501 - result += self._annotations_cache_key # type: ignore # noqa: E501 + if self._gen_static_annotations_cache_key: # type: ignore[attr-defined] # noqa: E501 + result += self._annotations_cache_key # type: ignore[attr-defined] # noqa: E501 else: - result += self._gen_annotations_cache_key(anon_map) # type: ignore # noqa: E501 + result += self._gen_annotations_cache_key(anon_map) # type: ignore[attr-defined] # noqa: E501 elif ( meth is InternalTraversal.dp_clauseelement_list @@ -341,7 +341,7 @@ class HasCacheKey: ), ) else: - result += meth( # type: ignore + result += meth( # type: ignore[misc, operator] attrname, obj, self, anon_map, bindparams ) return result @@ -430,7 +430,7 @@ class CacheKey(NamedTuple): # with namedtuple # can't use "if not TYPE_CHECKING" because mypy rejects it # inside of a NamedTuple - def __hash__(self) -> Optional[int]: # type: ignore + def __hash__(self) -> Optional[int]: # type: ignore[override] """CacheKey itself is not hashable - hash the .key portion""" return None diff --git a/lib/sqlalchemy/sql/compiler.py b/lib/sqlalchemy/sql/compiler.py index 2175326ce6..297f1a083a 100644 --- a/lib/sqlalchemy/sql/compiler.py +++ b/lib/sqlalchemy/sql/compiler.py @@ -1806,7 +1806,7 @@ class SQLCompiler(Compiled): ): # set to None to just mark the in positiontup, it will not # be replaced below. - param_pos[bind_name] = None # type: ignore + param_pos[bind_name] = None # type: ignore[assignment] else: ph = f"{self._numeric_binds_identifier_char}{num}" num += 1 @@ -1856,7 +1856,7 @@ class SQLCompiler(Compiled): # mypy is not able to see the two value types as the above Union, # it just sees "object". don't know how to resolve return { - key: value # type: ignore + key: value # type: ignore[misc] for key, value in ( ( self.bind_names[bindparam], diff --git a/lib/sqlalchemy/sql/crud.py b/lib/sqlalchemy/sql/crud.py index 793e465e0d..ed721d16ed 100644 --- a/lib/sqlalchemy/sql/crud.py +++ b/lib/sqlalchemy/sql/crud.py @@ -605,7 +605,7 @@ def _key_getters_for_crud_column( ) -> Union[str, Tuple[str, str]]: str_key = c_key_role(key) if hasattr(key, "table") and key.table in _et: - return (key.table.name, str_key) # type: ignore + return (key.table.name, str_key) # type: ignore[union-attr] else: return str_key @@ -613,7 +613,7 @@ def _key_getters_for_crud_column( col: ColumnClause[Any], ) -> Union[str, Tuple[str, str]]: if col.table in _et: - return (col.table.name, col.key) # type: ignore + return (col.table.name, col.key) # type: ignore[attr-defined] else: return col.key @@ -629,7 +629,7 @@ def _key_getters_for_crud_column( _column_as_key = functools.partial( coercions.expect_as_key, roles.DMLColumnRole ) - _getattr_col_key = _col_bind_name = operator.attrgetter("key") # type: ignore # noqa: E501 + _getattr_col_key = _col_bind_name = operator.attrgetter("key") # type: ignore[assignment] # noqa: E501 return _column_as_key, _getattr_col_key, _col_bind_name @@ -1354,7 +1354,7 @@ def _create_insert_prefetch_bind_param( param = _create_bind_param( compiler, c, None, process=process, name=name, **kw ) - compiler.insert_prefetch.append(c) # type: ignore + compiler.insert_prefetch.append(c) # type: ignore[attr-defined] return param @@ -1386,7 +1386,7 @@ def _create_update_prefetch_bind_param( param = _create_bind_param( compiler, c, None, process=process, name=name, **kw ) - compiler.update_prefetch.append(c) # type: ignore + compiler.update_prefetch.append(c) # type: ignore[attr-defined] return param diff --git a/lib/sqlalchemy/sql/ddl.py b/lib/sqlalchemy/sql/ddl.py index be40cdf877..a3be860d52 100644 --- a/lib/sqlalchemy/sql/ddl.py +++ b/lib/sqlalchemy/sql/ddl.py @@ -609,7 +609,7 @@ class _TableViaSelect(TableCreateDDL, ExecutableDDLElement): self._gen_table() @property - def element(self): # type: ignore + def element(self): # type: ignore[override] return self.table def to_metadata(self, metadata: MetaData, table: Table) -> Self: @@ -1777,7 +1777,7 @@ def sort_tables( return None else: - _skip_fn = None # type: ignore + _skip_fn = None # type: ignore[assignment] return [ t diff --git a/lib/sqlalchemy/sql/elements.py b/lib/sqlalchemy/sql/elements.py index c0b1ff38be..d5d8330062 100644 --- a/lib/sqlalchemy/sql/elements.py +++ b/lib/sqlalchemy/sql/elements.py @@ -419,7 +419,7 @@ class ClauseElement( def _default_compiler(self) -> SQLCompiler: dialect = self._default_dialect() - return dialect.statement_compiler(dialect, self) # type: ignore + return dialect.statement_compiler(dialect, self) # type: ignore[no-any-return] # noqa: E501 def _clone(self, **kw: Any) -> Self: """Create a shallow copy of this ClauseElement. @@ -2182,7 +2182,7 @@ class BindParameter(roles.InElementRole, KeyedColumnElement[_T]): """ if self.callable: # TODO: set up protocol for bind parameter callable - return self.callable() # type: ignore + return self.callable() # type: ignore[no-any-return] else: return self.value @@ -2373,7 +2373,7 @@ class AbstractTextClause( @property def comparator(self): - return self.type.comparator_factory(self) # type: ignore + return self.type.comparator_factory(self) # type: ignore[arg-type] def self_group( self, against: Optional[OperatorType] = None @@ -2723,7 +2723,7 @@ class TextClause(AbstractTextClause, inspection.Inspectable["TextClause"]): def comparator(self): # TODO: this seems wrong, it seems like we might not # be using this method. - return self.type.comparator_factory(self) # type: ignore + return self.type.comparator_factory(self) # type: ignore[arg-type] def self_group( self, against: Optional[OperatorType] = None @@ -3236,7 +3236,7 @@ class ExpressionClauseList(OperatorExpression[_T]): for clause in clauses ) self._is_implicitly_boolean = operators.is_boolean(self.operator) - self.type = type_api.to_instance(type_) # type: ignore + self.type = type_api.to_instance(type_) # type: ignore[assignment] @property def _flattened_operator_clauses( @@ -3397,7 +3397,7 @@ class BooleanClauseList(ExpressionClauseList[bool]): for to_flat in convert_clauses ) - return cls._construct_raw(operator, flattened_clauses) # type: ignore # noqa: E501 + return cls._construct_raw(operator, flattened_clauses) # type: ignore[arg-type] # noqa: E501 else: assert lcc # just one element. return it as a single boolean element, @@ -3929,7 +3929,7 @@ class UnaryExpression(ColumnElement[_T]): # if type is None, we get NULLTYPE, which is our _T. But I don't # know how to get the overloads to express that correctly - self.type = type_api.to_instance(type_) # type: ignore + self.type = type_api.to_instance(type_) # type: ignore[assignment] def _wraps_unnamed_column(self): ungrouped = self.element._ungroup() @@ -4236,7 +4236,7 @@ class BinaryExpression(OperatorExpression[_T]): # if type is None, we get NULLTYPE, which is our _T. But I don't # know how to get the overloads to express that correctly - self.type = type_api.to_instance(type_) # type: ignore + self.type = type_api.to_instance(type_) # type: ignore[assignment] self.negate = negate self._is_implicitly_boolean = operators.is_boolean(operator) @@ -4286,7 +4286,7 @@ class BinaryExpression(OperatorExpression[_T]): # this is using the eq/ne operator given int hash values, # rather than Operator, so that "bool" can be based on # identity - return self.operator(*self._orig) # type: ignore + return self.operator(*self._orig) # type: ignore[call-overload] else: raise TypeError("Boolean value of this clause is not defined") @@ -4406,7 +4406,7 @@ class Grouping(GroupedElement, ColumnElement[_T]): self.element = element # nulltype assignment issue - self.type = getattr(element, "type", type_api.NULLTYPE) # type: ignore + self.type = getattr(element, "type", type_api.NULLTYPE) # type: ignore[arg-type] # noqa: E501 self._propagate_attrs = element._propagate_attrs def _with_binary_element_type(self, type_): @@ -4930,7 +4930,7 @@ class FunctionFilter(Generative, ColumnElement[_T]): *criterion: _ColumnExpressionArgument[bool], ): self.func = func - self.filter.non_generative(self, *criterion) # type: ignore + self.filter.non_generative(self, *criterion) # type: ignore[attr-defined] # noqa: E501 @_generative def filter(self, *criterion: _ColumnExpressionArgument[bool]) -> Self: @@ -5420,7 +5420,7 @@ class ColumnClause( # if type is None, we get NULLTYPE, which is our _T. But I don't # know how to get the overloads to express that correctly - self.type = type_api.to_instance(type_) # type: ignore + self.type = type_api.to_instance(type_) # type: ignore[assignment] self.is_literal = is_literal @@ -5788,7 +5788,7 @@ def _type_from_args(args: Sequence[ColumnElement[_T]]) -> TypeEngine[_T]: if not a.type._isnull: return a.type else: - return type_api.NULLTYPE # type: ignore + return type_api.NULLTYPE # type: ignore[return-value] def _corresponding_column_or_error(fromclause, column, require_embedded=False): diff --git a/lib/sqlalchemy/sql/functions.py b/lib/sqlalchemy/sql/functions.py index 37e079aa60..968fec156b 100644 --- a/lib/sqlalchemy/sql/functions.py +++ b/lib/sqlalchemy/sql/functions.py @@ -896,7 +896,7 @@ class ScalarFunctionColumn(NamedColumn[_T]): # if type is None, we get NULLTYPE, which is our _T. But I don't # know how to get the overloads to express that correctly - self.type = type_api.to_instance(type_) # type: ignore + self.type = type_api.to_instance(type_) # type: ignore[assignment] class _FunctionGenerator: @@ -997,7 +997,7 @@ class _FunctionGenerator: # passthru __ attributes; fixes pydoc if name.startswith("__"): try: - return self.__dict__[name] # type: ignore + return self.__dict__[name] # type: ignore[no-any-return] except KeyError: raise AttributeError(name) @@ -1471,7 +1471,7 @@ class Function(FunctionElement[_T]): # if type is None, we get NULLTYPE, which is our _T. But I don't # know how to get the overloads to express that correctly - self.type = type_api.to_instance(type_) # type: ignore + self.type = type_api.to_instance(type_) # type: ignore[assignment] FunctionElement.__init__(self, *clauses) @@ -1656,13 +1656,13 @@ class GenericFunction(Function[_T]): ) ) - self.type = type_api.to_instance( # type: ignore + self.type = type_api.to_instance( # type: ignore[assignment] kwargs.pop("type_", None) or getattr(self, "type", None) ) -register_function("cast", Cast) # type: ignore -register_function("extract", Extract) # type: ignore +register_function("cast", Cast) # type: ignore[arg-type] +register_function("extract", Extract) # type: ignore[arg-type] class next_value(GenericFunction[int]): @@ -1687,7 +1687,7 @@ class next_value(GenericFunction[int]): seq, schema.Sequence ), "next_value() accepts a Sequence object as input." self.sequence = seq - self.type = sqltypes.to_instance( # type: ignore + self.type = sqltypes.to_instance( # type: ignore[assignment] seq.data_type or getattr(self, "type", None) ) @@ -1815,7 +1815,7 @@ class ReturnTypeFromOptionalArgs(ReturnTypeFromArgs[_T]): *args: _ColumnExpressionOrLiteralArgument[Optional[_T]], **kwargs: Any, ) -> None: - super().__init__(*args, **kwargs) # type: ignore + super().__init__(*args, **kwargs) # type: ignore[arg-type] class coalesce(ReturnTypeFromOptionalArgs[_T]): diff --git a/lib/sqlalchemy/sql/lambdas.py b/lib/sqlalchemy/sql/lambdas.py index 6ec217e8f8..d152c440f0 100644 --- a/lib/sqlalchemy/sql/lambdas.py +++ b/lib/sqlalchemy/sql/lambdas.py @@ -481,7 +481,7 @@ class DeferredLambdaElement(LambdaElement): for deferred_copy_internals in self._transforms: expr = deferred_copy_internals(expr) - return expr # type: ignore + return expr # type: ignore[no-any-return] def _copy_internals( self, clone=_clone, deferred_copy_internals=None, **kw diff --git a/lib/sqlalchemy/sql/operators.py b/lib/sqlalchemy/sql/operators.py index 2d0ae1a83d..f0c121e6f4 100644 --- a/lib/sqlalchemy/sql/operators.py +++ b/lib/sqlalchemy/sql/operators.py @@ -583,9 +583,9 @@ class custom_op(OperatorType, Generic[_T]): **kwargs: Any, ) -> Operators: if hasattr(left, "__sa_operate__"): - return left.operate(self, right, *other, **kwargs) # type: ignore + return left.operate(self, right, *other, **kwargs) # type: ignore[no-any-return] # noqa: E501 elif self.python_impl: - return self.python_impl(left, right, *other, **kwargs) # type: ignore # noqa: E501 + return self.python_impl(left, right, *other, **kwargs) # type: ignore[no-any-return] # noqa: E501 else: raise exc.InvalidRequestError( f"Custom operator {self.opstring!r} can't be used with " diff --git a/lib/sqlalchemy/sql/schema.py b/lib/sqlalchemy/sql/schema.py index 14958cc27b..368bb0897d 100644 --- a/lib/sqlalchemy/sql/schema.py +++ b/lib/sqlalchemy/sql/schema.py @@ -977,7 +977,7 @@ class Table( PrimaryKeyConstraint( _implicit_generated=True )._set_parent_with_dispatch(self) - self.foreign_keys = set() # type: ignore + self.foreign_keys = set() # type: ignore[misc] self._extra_dependencies: Set[Table] = set() if self.schema is not None: self.fullname = "%s.%s" % (self.schema, self.name) @@ -2329,7 +2329,7 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T], Named[_T]): raise exc.ArgumentError( "May not pass name positionally and as a keyword." ) - name = l_args.pop(0) # type: ignore + name = l_args.pop(0) # type: ignore[assignment] elif l_args[0] is None: l_args.pop(0) if l_args: @@ -2340,7 +2340,7 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T], Named[_T]): raise exc.ArgumentError( "May not pass type_ positionally and as a keyword." ) - type_ = l_args.pop(0) # type: ignore + type_ = l_args.pop(0) # type: ignore[assignment] elif l_args[0] is None: l_args.pop(0) @@ -2354,9 +2354,9 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T], Named[_T]): # name = None is expected to be an interim state # note this use case is legacy now that ORM declarative has a # dedicated "column" construct local to the ORM - super().__init__(name, type_) # type: ignore + super().__init__(name, type_) # type: ignore[arg-type] - self.key = key if key is not None else name # type: ignore + self.key = key if key is not None else name # type: ignore[assignment] self.primary_key = primary_key self._insert_sentinel = insert_sentinel self._omit_from_statements = _omit_from_statements @@ -2974,7 +2974,7 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T], Named[_T]): primary_key.add(c) if fk: - foreign_keys.update(fk) # type: ignore + foreign_keys.update(fk) # type: ignore[arg-type] return c.key, c @@ -3190,7 +3190,7 @@ class ForeignKey(DialectKWArgs, SchemaItem): self.constraint = _constraint # .parent is not Optional under normal use - self.parent = None # type: ignore + self.parent = None # type: ignore[assignment] self.use_alter = use_alter self.name = name @@ -3369,7 +3369,7 @@ class ForeignKey(DialectKWArgs, SchemaItem): # our column is a Column, and any subquery etc. proxying us # would be doing so via another Column, so that's what would # be returned here - return table.columns.corresponding_column(self.column) # type: ignore + return table.columns.corresponding_column(self.column) # type: ignore[return-value] # noqa: E501 @util.memoized_property def _column_tokens(self) -> Tuple[Optional[str], str, Optional[str]]: @@ -3490,7 +3490,7 @@ class ForeignKey(DialectKWArgs, SchemaItem): self.parent._setup_on_memoized_fks(set_type) - self.column = column # type: ignore + self.column = column # type: ignore[misc] @util.ro_memoized_property def column(self) -> Column[Any]: @@ -3942,16 +3942,16 @@ class CallableColumnDefault(ColumnDefault): try: argspec = util.get_callable_argspec(fn, no_self=True) except TypeError: - return util.wrap_callable(lambda ctx: fn(), fn) # type: ignore + return util.wrap_callable(lambda ctx: fn(), fn) # type: ignore[call-arg, no-any-return, no-untyped-call] # noqa: E501 defaulted = argspec[3] is not None and len(argspec[3]) or 0 positionals = len(argspec[0]) - defaulted if positionals == 0: - return util.wrap_callable(lambda ctx: fn(), fn) # type: ignore + return util.wrap_callable(lambda ctx: fn(), fn) # type: ignore[call-arg, no-any-return, no-untyped-call] # noqa: E501 elif positionals == 1: - return fn # type: ignore + return fn # type: ignore[return-value] else: raise exc.ArgumentError( "ColumnDefault Python function takes zero or one " @@ -5369,7 +5369,7 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint): if table.primary_key is not self: table.constraints.discard(table.primary_key) - table.primary_key = self # type: ignore + table.primary_key = self # type: ignore[misc] table.constraints.add(self) table_pks = [c for c in table.c if c.primary_key] @@ -5428,11 +5428,11 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint): self._columns.extend(columns) - PrimaryKeyConstraint._autoincrement_column._reset(self) # type: ignore + PrimaryKeyConstraint._autoincrement_column._reset(self) # type: ignore[attr-defined] # noqa: E501 self._set_parent_with_dispatch(self.table) def _replace(self, col: Column[Any]) -> None: - PrimaryKeyConstraint._autoincrement_column._reset(self) # type: ignore + PrimaryKeyConstraint._autoincrement_column._reset(self) # type: ignore[attr-defined] # noqa: E501 self._columns.replace(col) self.dispatch._sa_event_column_added_to_pk_constraint(self, col) @@ -6074,7 +6074,7 @@ class MetaData(HasSchemaAttr): """ return ddl.sort_tables( - sorted(self.tables.values(), key=lambda t: t.key) # type: ignore + sorted(self.tables.values(), key=lambda t: t.key) # type: ignore[attr-defined] # noqa: E501 ) # overload needed to work around mypy this mypy diff --git a/lib/sqlalchemy/sql/selectable.py b/lib/sqlalchemy/sql/selectable.py index 6b07bbf9b2..f6ce039064 100644 --- a/lib/sqlalchemy/sql/selectable.py +++ b/lib/sqlalchemy/sql/selectable.py @@ -674,7 +674,7 @@ class FromClause( At runtime returns self unchanged, without performing any validation. """ - return self # type: ignore + return self # type: ignore[return-value] @overload def select( @@ -963,8 +963,8 @@ class FromClause( # assigning these three collections separately is not itself # atomic, but greatly reduces the surface for problems self._columns = _columns - self.primary_key = primary_key # type: ignore - self.foreign_keys = foreign_keys # type: ignore + self.primary_key = primary_key # type: ignore[misc] + self.foreign_keys = foreign_keys # type: ignore[assignment, misc] @util.ro_non_memoized_property def entity_namespace(self) -> _EntityNamespace: @@ -1392,10 +1392,10 @@ class Join(roles.DMLTableRole, FromClause[_KeyColCC_co]): ) ) columns._populate_separate_keys( - (col._tq_key_label, col) for col in _columns # type: ignore + (col._tq_key_label, col) for col in _columns # type: ignore[misc] ) foreign_keys.update( - itertools.chain(*[col.foreign_keys for col in _columns]) # type: ignore # noqa: E501 + itertools.chain(*[col.foreign_keys for col in _columns]) # type: ignore[arg-type] # noqa: E501 ) def _copy_internals( @@ -1811,7 +1811,7 @@ class AliasedReturnsRows(NoInit, NamedFromClause[_KeyColCC_co]): @util.ro_non_memoized_property def implicit_returning(self) -> bool: - return self.element.implicit_returning # type: ignore + return self.element.implicit_returning # type: ignore[attr-defined, no-any-return] # noqa: E501 @property def original(self) -> ReturnsRows: @@ -3216,8 +3216,8 @@ class TableClause( super().__init__() self.name = name self._columns = DedupeColumnCollection() # type: ignore[unused-ignore] - self.primary_key = ColumnSet() # type: ignore - self.foreign_keys = set() # type: ignore + self.primary_key = ColumnSet() # type: ignore[misc] + self.foreign_keys = set() # type: ignore[misc] for c in columns: self.append_column(c) @@ -5130,7 +5130,7 @@ class SelectState(util.MemoizedSlots, CompileState): if c._allow_label_resolve } only_froms: Dict[str, ColumnElement[Any]] = { - c.key: c # type: ignore + c.key: c # type: ignore[misc] for c in _select_iterables(self.froms) if c._allow_label_resolve } @@ -6455,7 +6455,7 @@ class Select( self._assert_no_memoizations() if maintain_column_froms: - self.select_from.non_generative( # type: ignore + self.select_from.non_generative( # type: ignore[attr-defined] self, *self.columns_clause_froms ) @@ -7513,14 +7513,14 @@ class AnnotatedFromClause(Annotated): # cases. in other cases such as plain visitors.cloned_traverse(), we # expect this to happen. see issue #12915 if not _annotations_traversal: - ee = self._Annotated__element # type: ignore + ee = self._Annotated__element # type: ignore[attr-defined] ee._copy_internals(**kw) if ind_cols_on_fromclause: # passed from annotations._deep_annotate(). See that function # for notes - ee = self._Annotated__element # type: ignore - self.c = ee.__class__.c.fget(self) # type: ignore + ee = self._Annotated__element # type: ignore[attr-defined] + self.c = ee.__class__.c.fget(self) # type: ignore[misc] @util.ro_memoized_property def c(self) -> ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]: @@ -7538,5 +7538,5 @@ class AnnotatedFromClause(Annotated): See test_selectable->test_annotated_corresponding_column """ - ee = self._Annotated__element # type: ignore - return ee.c # type: ignore + ee = self._Annotated__element # type: ignore[attr-defined] + return ee.c # type: ignore[no-any-return] diff --git a/lib/sqlalchemy/sql/sqltypes.py b/lib/sqlalchemy/sql/sqltypes.py index 459d44a650..1d1505d06b 100644 --- a/lib/sqlalchemy/sql/sqltypes.py +++ b/lib/sqlalchemy/sql/sqltypes.py @@ -1770,7 +1770,7 @@ class Enum(String, SchemaType, Emulated, TypeEngine[Union[str, enum.Enum]]): kw["length"] = NO_ARG if self.length == 0 else self.length return cast( Enum, - self._generic_type_affinity(_enums=enum_args, **kw), # type: ignore # noqa: E501 + self._generic_type_affinity(_enums=enum_args, **kw), # type: ignore[call-arg] # noqa: E501 ) def _setup_for_values( @@ -2036,7 +2036,7 @@ class PickleType(TypeDecorator[object]): if impl: # custom impl is not necessarily a LargeBinary subclass. # make an exception to typing for this - self.impl = to_instance(impl) # type: ignore + self.impl = to_instance(impl) # type: ignore[assignment] def __reduce__(self): return PickleType, (self.protocol, None, self.comparator) @@ -2375,7 +2375,7 @@ class Interval(Emulated, _AbstractInterval, TypeDecorator[dt.timedelta]): def process(value: Any) -> Optional[dt.timedelta]: if value is None: return None - return value - epoch # type: ignore + return value - epoch # type: ignore[no-any-return] return process diff --git a/lib/sqlalchemy/sql/traversals.py b/lib/sqlalchemy/sql/traversals.py index 99d3219c10..ff22303a45 100644 --- a/lib/sqlalchemy/sql/traversals.py +++ b/lib/sqlalchemy/sql/traversals.py @@ -140,7 +140,7 @@ class HasShallowCopy(HasTraverseInternals): "_generated_shallow_from_dict_traversal", ) - cls._generated_shallow_from_dict_traversal = shallow_from_dict # type: ignore # noqa: E501 + cls._generated_shallow_from_dict_traversal = shallow_from_dict # type: ignore[assignment, method-assign] # noqa: E501 shallow_from_dict(self, d) @@ -158,7 +158,7 @@ class HasShallowCopy(HasTraverseInternals): cls._traverse_internals, "_generated_shallow_to_dict_traversal" ) - cls._generated_shallow_to_dict_traversal = shallow_to_dict # type: ignore # noqa: E501 + cls._generated_shallow_to_dict_traversal = shallow_to_dict # type: ignore[assignment, method-assign] # noqa: E501 return shallow_to_dict(self) def _shallow_copy_to(self, other: Self) -> None: @@ -172,7 +172,7 @@ class HasShallowCopy(HasTraverseInternals): cls._traverse_internals, "_generated_shallow_copy_traversal" ) - cls._generated_shallow_copy_traversal = shallow_copy # type: ignore # noqa: E501 + cls._generated_shallow_copy_traversal = shallow_copy # type: ignore[assignment, method-assign] # noqa: E501 shallow_copy(self, other) def _clone(self, **kw: Any) -> Self: diff --git a/lib/sqlalchemy/sql/type_api.py b/lib/sqlalchemy/sql/type_api.py index cd04ca0e11..5999027b0b 100644 --- a/lib/sqlalchemy/sql/type_api.py +++ b/lib/sqlalchemy/sql/type_api.py @@ -1153,7 +1153,7 @@ class TypeEngine(Visitable, Generic[_T]): # dmypy / mypy seems to sporadically keep thinking this line is # returning Any, which seems to be caused by the @deprecated_params # decorator on the DefaultDialect constructor - return default.StrCompileDialect() # type: ignore + return default.StrCompileDialect() # type: ignore[no-any-return] def __str__(self) -> str: return str(self.compile()) @@ -1574,7 +1574,7 @@ class NativeForEmulated(TypeEngineMixin): """ # dmypy seems to crash on this - return cls(**kw) # type: ignore + return cls(**kw) # type: ignore[return-value] # dmypy seems to crash with this, on repeated runs with changes # if TYPE_CHECKING: @@ -1741,7 +1741,7 @@ class TypeDecorator(SchemaEventTarget, ExternalType, TypeEngine[_T]): # impl_instance. @util.memoized_property def impl_instance(self) -> TypeEngine[Any]: - return self.impl # type: ignore + return self.impl # type: ignore[return-value] def __init__(self, *args: Any, **kwargs: Any): """Construct a :class:`.TypeDecorator`. @@ -1838,15 +1838,15 @@ class TypeDecorator(SchemaEventTarget, ExternalType, TypeEngine[_T]): return type( "TDComparator", - (TypeDecorator.Comparator, impl.comparator_factory), # type: ignore # noqa: E501 + (TypeDecorator.Comparator, impl.comparator_factory), # type: ignore[arg-type, return-value] # noqa: E501 {"__reduce__": __reduce__}, ) @property - def comparator_factory( # type: ignore # mypy properties bug + def comparator_factory( # type: ignore[override] # mypy properties bug self, ) -> _ComparatorFactory[Any]: - if TypeDecorator.Comparator in self.impl.comparator_factory.__mro__: # type: ignore # noqa: E501 + if TypeDecorator.Comparator in self.impl.comparator_factory.__mro__: # type: ignore[attr-defined] # noqa: E501 return self.impl_instance.comparator_factory else: # reconcile the Comparator class on the impl with that @@ -2370,7 +2370,7 @@ class TypeDecorator(SchemaEventTarget, ExternalType, TypeEngine[_T]): # mypy property bug @property - def sort_key_function(self) -> Optional[Callable[[Any], Any]]: # type: ignore # noqa: E501 + def sort_key_function(self) -> Optional[Callable[[Any], Any]]: # type: ignore[override] # noqa: E501 return self.impl_instance.sort_key_function def repr_struct(self) -> util.GenericRepr: diff --git a/lib/sqlalchemy/sql/util.py b/lib/sqlalchemy/sql/util.py index 9b129ae499..95aad914d1 100644 --- a/lib/sqlalchemy/sql/util.py +++ b/lib/sqlalchemy/sql/util.py @@ -304,11 +304,11 @@ def visit_binary_product( # those are just column elements by themselves yield element elif element.__visit_name__ == "binary" and operators.is_comparison( - element.operator # type: ignore + element.operator # type: ignore[attr-defined] ): - stack.insert(0, element) # type: ignore - for l in visit(element.left): # type: ignore - for r in visit(element.right): # type: ignore + stack.insert(0, element) # type: ignore[arg-type] + for l in visit(element.left): # type: ignore[attr-defined] + for r in visit(element.right): # type: ignore[attr-defined] fn(stack[0], l, r) stack.pop(0) for elem in element.get_children(): @@ -320,7 +320,7 @@ def visit_binary_product( yield from visit(elem) list(visit(expr)) - visit = None # type: ignore # remove gc cycles + visit = None # type: ignore[assignment] # remove gc cycles def find_tables( @@ -384,7 +384,7 @@ def unwrap_order_by(clause: Any) -> Any: t = stack.popleft() if isinstance(t, ColumnElement) and ( not isinstance(t, UnaryExpression) - or not operators.is_ordering_modifier(t.modifier) # type: ignore + or not operators.is_ordering_modifier(t.modifier) # type: ignore[arg-type] # noqa: E501 ): if isinstance(t, Label) and not isinstance( t.element, ScalarSelect @@ -926,7 +926,7 @@ def reduce_columns( column_set = util.OrderedSet(columns) cset_no_text: util.OrderedSet[ColumnElement[Any]] = column_set.difference( - c for c in column_set if is_text_clause(c) # type: ignore + c for c in column_set if is_text_clause(c) # type: ignore[assignment] ) omit = util.column_set() @@ -1158,9 +1158,9 @@ class ClauseAdapter(visitors.ReplacingExternalTraversal): # TODO: cython candidate - if self.include_fn and not self.include_fn(col): # type: ignore + if self.include_fn and not self.include_fn(col): # type: ignore[arg-type] # noqa: E501 return None - elif self.exclude_fn and self.exclude_fn(col): # type: ignore + elif self.exclude_fn and self.exclude_fn(col): # type: ignore[arg-type] # noqa: E501 return None if isinstance(col, FromClause) and not isinstance( @@ -1173,7 +1173,7 @@ class ClauseAdapter(visitors.ReplacingExternalTraversal): break else: return None - return self.selectable # type: ignore + return self.selectable # type: ignore[return-value] elif isinstance(col, Alias) and isinstance( col.element, TableClause ): @@ -1219,7 +1219,7 @@ class ClauseAdapter(visitors.ReplacingExternalTraversal): if TYPE_CHECKING: assert isinstance(col, KeyedColumnElement) - return self._corresponding_column( # type: ignore + return self._corresponding_column( # type: ignore[no-any-return] col, require_embedded=True ) @@ -1303,7 +1303,7 @@ class ColumnAdapter(ClauseAdapter): adapt_from_selectables=adapt_from_selectables, ) - self.columns = util.WeakPopulateDict(self._locate_col) # type: ignore + self.columns = util.WeakPopulateDict(self._locate_col) # type: ignore[arg-type, assignment] # noqa: E501 if self.include_fn or self.exclude_fn: self.columns = self._IncludeExcludeMapping(self, self.columns) self.adapt_required = adapt_required @@ -1328,7 +1328,7 @@ class ColumnAdapter(ClauseAdapter): def wrap(self, adapter): ac = copy.copy(self) ac._wrap = adapter - ac.columns = util.WeakPopulateDict(ac._locate_col) # type: ignore + ac.columns = util.WeakPopulateDict(ac._locate_col) # type: ignore[arg-type, assignment] # noqa: E501 if ac.include_fn or ac.exclude_fn: ac.columns = self._IncludeExcludeMapping(ac, ac.columns) @@ -1466,7 +1466,7 @@ def _make_slice( offset_clause = 0 if start != 0: - offset_clause = offset_clause + start # type: ignore + offset_clause = offset_clause + start # type: ignore[operator] if offset_clause == 0: offset_clause = None diff --git a/lib/sqlalchemy/sql/visitors.py b/lib/sqlalchemy/sql/visitors.py index 3cfe6a54e2..44c080b117 100644 --- a/lib/sqlalchemy/sql/visitors.py +++ b/lib/sqlalchemy/sql/visitors.py @@ -123,11 +123,11 @@ class Visitable: try: meth = getter(visitor) except AttributeError as err: - return visitor.visit_unsupported_compilation(self, err, **kw) # type: ignore # noqa: E501 + return visitor.visit_unsupported_compilation(self, err, **kw) # type: ignore[no-any-return] # noqa: E501 else: - return meth(self, **kw) # type: ignore # noqa: E501 + return meth(self, **kw) # type: ignore[no-any-return] # noqa: E501 - cls._compiler_dispatch = ( # type: ignore + cls._compiler_dispatch = ( # type: ignore[method-assign] cls._original_compiler_dispatch ) = _compiler_dispatch @@ -501,7 +501,7 @@ class HasTraversalDispatch: """ name = _dispatch_lookup[visit_symbol] - return getattr(self, name, None) # type: ignore + return getattr(self, name, None) # type: ignore[return-value] def run_generated_dispatch( self, @@ -1132,7 +1132,7 @@ def replacement_traverse( newelem = replace(elem) if newelem is not None: stop_on.add(id(newelem)) - return newelem # type: ignore + return newelem # type: ignore[no-any-return] else: # base "already seen" on id(), not hash, so that we don't # replace an Annotated element with its non-annotated one, and @@ -1143,11 +1143,11 @@ def replacement_traverse( newelem = kw["replace"](elem) if newelem is not None: cloned[id_elem] = newelem - return newelem # type: ignore + return newelem # type: ignore[no-any-return] cloned[id_elem] = newelem = elem._clone(**kw) newelem._copy_internals(clone=clone, **kw) - return cloned[id_elem] # type: ignore + return cloned[id_elem] # type: ignore[no-any-return] if obj is not None: obj = clone( diff --git a/lib/sqlalchemy/util/_collections.py b/lib/sqlalchemy/util/_collections.py index 2034d92a23..5843dd7311 100644 --- a/lib/sqlalchemy/util/_collections.py +++ b/lib/sqlalchemy/util/_collections.py @@ -388,7 +388,7 @@ def coerce_generator_arg(arg: Any) -> List[Any]: def to_list(x: Any, default: Optional[List[Any]] = None) -> List[Any]: if x is None: - return default # type: ignore + return default # type: ignore[return-value] if not is_non_string_iterable(x): return [x] elif isinstance(x, list): @@ -539,7 +539,7 @@ class LRUCache(typing.MutableMapping[_KT, _VT]): while len(self) > self.capacity + self.capacity * self.threshold: if size_alert: size_alert = False - self.size_alert(self) # type: ignore + self.size_alert(self) # type: ignore[misc] by_counter = sorted( self._data.values(), key=operator.itemgetter(2), diff --git a/lib/sqlalchemy/util/deprecations.py b/lib/sqlalchemy/util/deprecations.py index 316dead585..70edf7660c 100644 --- a/lib/sqlalchemy/util/deprecations.py +++ b/lib/sqlalchemy/util/deprecations.py @@ -395,7 +395,7 @@ def _decorate_with_warning( decorated = warned(func) decorated.__doc__ = doc - decorated._sa_warn = lambda: _warn_with_version( # type: ignore + decorated._sa_warn = lambda: _warn_with_version( # type: ignore[attr-defined] # noqa: E501 message, version, wtype, stacklevel=3 ) return decorated diff --git a/lib/sqlalchemy/util/langhelpers.py b/lib/sqlalchemy/util/langhelpers.py index f4efad3340..20c4979064 100644 --- a/lib/sqlalchemy/util/langhelpers.py +++ b/lib/sqlalchemy/util/langhelpers.py @@ -340,7 +340,7 @@ def decorator(target: Callable[..., Any]) -> Callable[[_Fn], _Fn]: _exec_code_in_env(code, env, fn.__name__), ) decorated.__defaults__ = fn.__defaults__ - decorated.__kwdefaults__ = fn.__kwdefaults__ # type: ignore + decorated.__kwdefaults__ = fn.__kwdefaults__ # type: ignore[union-attr] # noqa: E501 return update_wrapper(decorated, fn) # type: ignore[return-value] return update_wrapper(decorate, target) # type: ignore[return-value] @@ -1268,7 +1268,7 @@ def memoized_instancemethod(fn: _F) -> _F: self.__dict__[fn.__name__] = memo return result - return update_wrapper(oneshot, fn) # type: ignore + return update_wrapper(oneshot, fn) # type: ignore[return-value] class HasMemoized: @@ -1345,7 +1345,7 @@ class HasMemoized: self._memoized_keys |= {fn.__name__} return result - return update_wrapper(oneshot, fn) # type: ignore + return update_wrapper(oneshot, fn) # type: ignore[return-value] if TYPE_CHECKING: @@ -1518,7 +1518,7 @@ def duck_type_collection( ): return set else: - return specimen.__emulates__ # type: ignore + return specimen.__emulates__ # type: ignore[no-any-return] isa = issubclass if isinstance(specimen, type) else isinstance if isa(specimen, list): diff --git a/lib/sqlalchemy/util/typing.py b/lib/sqlalchemy/util/typing.py index 4c7a4ba58c..2d1ed00654 100644 --- a/lib/sqlalchemy/util/typing.py +++ b/lib/sqlalchemy/util/typing.py @@ -163,7 +163,7 @@ def de_stringify_annotation( # will always be Type. # the element here will be either ForwardRef or # Optional[ForwardRef] - return original_annotation # type: ignore + return original_annotation # type: ignore[return-value] else: _already_seen.add(annotation) @@ -182,7 +182,7 @@ def de_stringify_annotation( return _copy_generic_annotation_with(annotation, elements) - return annotation # type: ignore + return annotation # type: ignore[return-value] def fixup_container_fwd_refs( @@ -215,7 +215,7 @@ def fixup_container_fwd_refs( ) ): # compat with py3.10 and earlier - return get_origin(type_).__class_getitem__( # type: ignore + return get_origin(type_).__class_getitem__( # type: ignore[no-any-return, union-attr] # noqa: E501 tuple( [ ForwardRef(elem) if isinstance(elem, str) else elem @@ -231,10 +231,10 @@ def _copy_generic_annotation_with( ) -> Type[_T]: if hasattr(annotation, "copy_with"): # List, Dict, etc. real generics - return annotation.copy_with(elements) # type: ignore + return annotation.copy_with(elements) # type: ignore[no-any-return] else: # Python builtins list, dict, etc. - return annotation.__origin__[elements] # type: ignore + return annotation.__origin__[elements] # type: ignore[no-any-return] def eval_expression( @@ -534,7 +534,7 @@ def _de_optionalize_fwd_ref_union_types( def make_union_type(*types: _AnnotationScanType) -> Type[Any]: """Make a Union type.""" - return Union[types] # type: ignore + return Union[types] # type: ignore[return-value] def includes_none(type_: Any) -> bool: diff --git a/pyproject.toml b/pyproject.toml index 1c5837b711..9b750e318d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,7 +45,7 @@ Discussions = "https://github.com/sqlalchemy/sqlalchemy/discussions" [project.optional-dependencies] asyncio = ["greenlet>=1"] mypy = [ - "mypy >= 2", + "mypy >= 2.3", "types-greenlet >= 2", ] mssql = ["pyodbc"] @@ -333,8 +333,7 @@ reportTypedDictNotRequiredAccess = "warning" mypy_path = "./lib/" show_error_codes = true incremental = true -# would be nice to enable this but too many error are surfaceds -# enable_error_code = "ignore-without-code" +enable_error_code = "ignore-without-code" [[tool.mypy.overrides]] diff --git a/tools/toxnox.py b/tools/toxnox.py index 2bdcebd301..c91192b3c8 100644 --- a/tools/toxnox.py +++ b/tools/toxnox.py @@ -190,7 +190,7 @@ def extract_opts(posargs: list[str], *args: str) -> tuple[list[str], Any]: """ underscore_args = [arg.replace("-", "_") for arg in args] - return_tuple = collections.namedtuple("options", underscore_args) # type: ignore # noqa: E501 + return_tuple = collections.namedtuple("options", underscore_args) # type: ignore[misc] # noqa: E501 look_for_args = {f"--{arg}": idx for idx, arg in enumerate(args)} return_args = [False for arg in args] diff --git a/tox.ini b/tox.ini index 4aa5facea5..f9ab0c0084 100644 --- a/tox.ini +++ b/tox.ini @@ -203,7 +203,7 @@ commands= [testenv:pep484] deps= greenlet >= 1 - mypy >= 2 + mypy >= 2.3 types-greenlet commands = mypy {env:MYPY_COLOR} ./lib/sqlalchemy