diff options
| author | Mike Bayer <mike_mp@zzzcomputing.com> | 2020-09-28 14:08:59 -0400 |
|---|---|---|
| committer | Mike Bayer <mike_mp@zzzcomputing.com> | 2020-09-28 15:17:26 -0400 |
| commit | c3f102c9fe9811fd5286628cc6aafa5fbc324621 (patch) | |
| tree | 4a78723089ded623701667de1eee21d22edbe6c1 /lib | |
| parent | 75ac0abc7d5653d10006769a881374a46b706db5 (diff) | |
| download | sqlalchemy-c3f102c9fe9811fd5286628cc6aafa5fbc324621.tar.gz | |
upgrade to black 20.8b1
It's better, the majority of these changes look more readable to me.
also found some docstrings that had formatting / quoting issues.
Change-Id: I582a45fde3a5648b2f36bab96bad56881321899b
Diffstat (limited to 'lib')
75 files changed, 436 insertions, 304 deletions
diff --git a/lib/sqlalchemy/connectors/mxodbc.py b/lib/sqlalchemy/connectors/mxodbc.py index e243aba80..e630f36e3 100644 --- a/lib/sqlalchemy/connectors/mxodbc.py +++ b/lib/sqlalchemy/connectors/mxodbc.py @@ -66,7 +66,7 @@ class MxODBCConnector(Connector): @classmethod def _load_mx_exceptions(cls): - """ Import mxODBC exception classes into the module namespace, + """Import mxODBC exception classes into the module namespace, as if they had been imported normally. This is done here to avoid requiring all SQLAlchemy users to install mxODBC. """ @@ -84,7 +84,7 @@ class MxODBCConnector(Connector): return connect def _error_handler(self): - """ Return a handler that adjusts mxODBC's raised Warnings to + """Return a handler that adjusts mxODBC's raised Warnings to emit Python standard warnings. """ from mx.ODBC.Error import Warning as MxOdbcWarning diff --git a/lib/sqlalchemy/dialects/mssql/base.py b/lib/sqlalchemy/dialects/mssql/base.py index 2cbdc19aa..87ccc8427 100644 --- a/lib/sqlalchemy/dialects/mssql/base.py +++ b/lib/sqlalchemy/dialects/mssql/base.py @@ -1033,7 +1033,7 @@ class TIME(sqltypes.TIME): self.__zero_date, value.time() ) elif isinstance(value, datetime.time): - """ issue #5339 + """issue #5339 per: https://github.com/mkleehammer/pyodbc/wiki/Tips-and-Tricks-by-Database-Platform#time-columns pass TIME value as string """ # noqa @@ -1260,9 +1260,7 @@ class SQL_VARIANT(sqltypes.TypeEngine): class TryCast(sql.elements.Cast): - """Represent a SQL Server TRY_CAST expression. - - """ + """Represent a SQL Server TRY_CAST expression.""" __visit_name__ = "try_cast" @@ -1579,8 +1577,12 @@ class MSExecutionContext(default.DefaultExecutionContext): elif ( self.isinsert or self.isupdate or self.isdelete ) and self.compiled.returning: - self.cursor_fetch_strategy = _cursor.FullyBufferedCursorFetchStrategy( # noqa - self.cursor, self.cursor.description, self.cursor.fetchall() + self.cursor_fetch_strategy = ( + _cursor.FullyBufferedCursorFetchStrategy( + self.cursor, + self.cursor.description, + self.cursor.fetchall(), + ) ) if self._enable_identity_insert: @@ -1729,8 +1731,8 @@ class MSSQLCompiler(compiler.SQLCompiler): return text def limit_clause(self, select, **kw): - """ MSSQL 2012 supports OFFSET/FETCH operators - Use it instead subquery with row_number + """MSSQL 2012 supports OFFSET/FETCH operators + Use it instead subquery with row_number """ diff --git a/lib/sqlalchemy/dialects/mssql/mxodbc.py b/lib/sqlalchemy/dialects/mssql/mxodbc.py index 998153d7a..b274c2a2b 100644 --- a/lib/sqlalchemy/dialects/mssql/mxodbc.py +++ b/lib/sqlalchemy/dialects/mssql/mxodbc.py @@ -59,8 +59,7 @@ from ...connectors.mxodbc import MxODBCConnector class _MSNumeric_mxodbc(_MSNumeric_pyodbc): - """Include pyodbc's numeric processor. - """ + """Include pyodbc's numeric processor.""" class _MSDate_mxodbc(_MSDate): diff --git a/lib/sqlalchemy/dialects/mysql/cymysql.py b/lib/sqlalchemy/dialects/mysql/cymysql.py index 2b45f5ddb..f1d0aedaf 100644 --- a/lib/sqlalchemy/dialects/mysql/cymysql.py +++ b/lib/sqlalchemy/dialects/mysql/cymysql.py @@ -28,8 +28,7 @@ from ... import util class _cymysqlBIT(BIT): def result_processor(self, dialect, coltype): - """Convert a MySQL's 64 bit, variable length binary string to a long. - """ + """Convert MySQL's 64 bit, variable length binary string to a long.""" def process(value): if value is not None: diff --git a/lib/sqlalchemy/dialects/mysql/mariadb.py b/lib/sqlalchemy/dialects/mysql/mariadb.py index c6cadcd60..0dbb579e8 100644 --- a/lib/sqlalchemy/dialects/mysql/mariadb.py +++ b/lib/sqlalchemy/dialects/mysql/mariadb.py @@ -13,5 +13,10 @@ def loader(driver): driver_cls = getattr(driver_mod, driver).dialect return type( - "MariaDBDialect_%s" % driver, (MariaDBDialect, driver_cls,), {} + "MariaDBDialect_%s" % driver, + ( + MariaDBDialect, + driver_cls, + ), + {}, ) diff --git a/lib/sqlalchemy/dialects/mysql/types.py b/lib/sqlalchemy/dialects/mysql/types.py index 3b455cfb1..594975000 100644 --- a/lib/sqlalchemy/dialects/mysql/types.py +++ b/lib/sqlalchemy/dialects/mysql/types.py @@ -440,9 +440,7 @@ class TIME(sqltypes.TIME): class TIMESTAMP(sqltypes.TIMESTAMP): - """MySQL TIMESTAMP type. - - """ + """MySQL TIMESTAMP type.""" __visit_name__ = "TIMESTAMP" @@ -467,9 +465,7 @@ class TIMESTAMP(sqltypes.TIMESTAMP): class DATETIME(sqltypes.DATETIME): - """MySQL DATETIME type. - - """ + """MySQL DATETIME type.""" __visit_name__ = "DATETIME" diff --git a/lib/sqlalchemy/dialects/oracle/cx_oracle.py b/lib/sqlalchemy/dialects/oracle/cx_oracle.py index 651a6e673..d1b69100f 100644 --- a/lib/sqlalchemy/dialects/oracle/cx_oracle.py +++ b/lib/sqlalchemy/dialects/oracle/cx_oracle.py @@ -970,7 +970,11 @@ class OracleDialect_cx_oracle(OracleDialect): # allow all strings to come back natively as Unicode elif ( dialect.coerce_to_unicode - and default_type in (cx_Oracle.STRING, cx_Oracle.FIXED_CHAR,) + and default_type + in ( + cx_Oracle.STRING, + cx_Oracle.FIXED_CHAR, + ) and default_type is not cx_Oracle.CLOB and default_type is not cx_Oracle.NCLOB ): @@ -1018,7 +1022,9 @@ class OracleDialect_cx_oracle(OracleDialect): cx_Oracle.BLOB, ): return cursor.var( - cx_Oracle.LONG_BINARY, size, cursor.arraysize, + cx_Oracle.LONG_BINARY, + size, + cursor.arraysize, ) return output_type_handler diff --git a/lib/sqlalchemy/dialects/postgresql/asyncpg.py b/lib/sqlalchemy/dialects/postgresql/asyncpg.py index 1f988153c..8b20de2b6 100644 --- a/lib/sqlalchemy/dialects/postgresql/asyncpg.py +++ b/lib/sqlalchemy/dialects/postgresql/asyncpg.py @@ -576,11 +576,13 @@ class AsyncAdapt_asyncpg_dbapi: if async_fallback: return AsyncAdaptFallback_asyncpg_connection( - self, await_fallback(self.asyncpg.connect(*arg, **kw)), + self, + await_fallback(self.asyncpg.connect(*arg, **kw)), ) else: return AsyncAdapt_asyncpg_connection( - self, await_only(self.asyncpg.connect(*arg, **kw)), + self, + await_only(self.asyncpg.connect(*arg, **kw)), ) class Error(Exception): diff --git a/lib/sqlalchemy/dialects/postgresql/base.py b/lib/sqlalchemy/dialects/postgresql/base.py index 878693866..5ed56db56 100644 --- a/lib/sqlalchemy/dialects/postgresql/base.py +++ b/lib/sqlalchemy/dialects/postgresql/base.py @@ -1338,9 +1338,7 @@ class TIME(sqltypes.TIME): class INTERVAL(sqltypes.NativeForEmulated, sqltypes._AbstractInterval): - """PostgreSQL INTERVAL type. - - """ + """PostgreSQL INTERVAL type.""" __visit_name__ = "INTERVAL" native = True @@ -1414,7 +1412,7 @@ class UUID(sqltypes.TypeEngine): as Python uuid objects, converting to/from string via the DBAPI. - """ + """ self.as_uuid = as_uuid def coerce_compared_value(self, op, value): @@ -3026,7 +3024,9 @@ class PGDialect(default.DefaultDialect): type_=sqltypes.Unicode, ), sql.bindparam( - "schema", util.text_type(schema), type_=sqltypes.Unicode, + "schema", + util.text_type(schema), + type_=sqltypes.Unicode, ), ) ) @@ -3200,7 +3200,9 @@ class PGDialect(default.DefaultDialect): "n.nspname=:schema" ).bindparams( sql.bindparam( - "schema", util.text_type(schema), type_=sqltypes.Unicode, + "schema", + util.text_type(schema), + type_=sqltypes.Unicode, ), ) ) diff --git a/lib/sqlalchemy/dialects/postgresql/hstore.py b/lib/sqlalchemy/dialects/postgresql/hstore.py index cb89f7c5f..15ec2a585 100644 --- a/lib/sqlalchemy/dialects/postgresql/hstore.py +++ b/lib/sqlalchemy/dialects/postgresql/hstore.py @@ -160,13 +160,11 @@ class HSTORE(sqltypes.Indexable, sqltypes.Concatenable, sqltypes.TypeEngine): return self.operate(HAS_KEY, other, result_type=sqltypes.Boolean) def has_all(self, other): - """Boolean expression. Test for presence of all keys in jsonb - """ + """Boolean expression. Test for presence of all keys in jsonb""" return self.operate(HAS_ALL, other, result_type=sqltypes.Boolean) def has_any(self, other): - """Boolean expression. Test for presence of any key in jsonb - """ + """Boolean expression. Test for presence of any key in jsonb""" return self.operate(HAS_ANY, other, result_type=sqltypes.Boolean) def contains(self, other, **kwargs): diff --git a/lib/sqlalchemy/dialects/postgresql/json.py b/lib/sqlalchemy/dialects/postgresql/json.py index 9ffe9cfe8..63e1656e0 100644 --- a/lib/sqlalchemy/dialects/postgresql/json.py +++ b/lib/sqlalchemy/dialects/postgresql/json.py @@ -204,7 +204,7 @@ class JSON(sqltypes.JSON): .. versionadded:: 1.1 - """ + """ super(JSON, self).__init__(none_as_null=none_as_null) if astext_type is not None: self.astext_type = astext_type @@ -300,13 +300,11 @@ class JSONB(JSON): return self.operate(HAS_KEY, other, result_type=sqltypes.Boolean) def has_all(self, other): - """Boolean expression. Test for presence of all keys in jsonb - """ + """Boolean expression. Test for presence of all keys in jsonb""" return self.operate(HAS_ALL, other, result_type=sqltypes.Boolean) def has_any(self, other): - """Boolean expression. Test for presence of any key in jsonb - """ + """Boolean expression. Test for presence of any key in jsonb""" return self.operate(HAS_ANY, other, result_type=sqltypes.Boolean) def contains(self, other, **kwargs): diff --git a/lib/sqlalchemy/dialects/postgresql/ranges.py b/lib/sqlalchemy/dialects/postgresql/ranges.py index a31d958ed..ddc12c096 100644 --- a/lib/sqlalchemy/dialects/postgresql/ranges.py +++ b/lib/sqlalchemy/dialects/postgresql/ranges.py @@ -100,48 +100,36 @@ class RangeOperators(object): class INT4RANGE(RangeOperators, sqltypes.TypeEngine): - """Represent the PostgreSQL INT4RANGE type. - - """ + """Represent the PostgreSQL INT4RANGE type.""" __visit_name__ = "INT4RANGE" class INT8RANGE(RangeOperators, sqltypes.TypeEngine): - """Represent the PostgreSQL INT8RANGE type. - - """ + """Represent the PostgreSQL INT8RANGE type.""" __visit_name__ = "INT8RANGE" class NUMRANGE(RangeOperators, sqltypes.TypeEngine): - """Represent the PostgreSQL NUMRANGE type. - - """ + """Represent the PostgreSQL NUMRANGE type.""" __visit_name__ = "NUMRANGE" class DATERANGE(RangeOperators, sqltypes.TypeEngine): - """Represent the PostgreSQL DATERANGE type. - - """ + """Represent the PostgreSQL DATERANGE type.""" __visit_name__ = "DATERANGE" class TSRANGE(RangeOperators, sqltypes.TypeEngine): - """Represent the PostgreSQL TSRANGE type. - - """ + """Represent the PostgreSQL TSRANGE type.""" __visit_name__ = "TSRANGE" class TSTZRANGE(RangeOperators, sqltypes.TypeEngine): - """Represent the PostgreSQL TSTZRANGE type. - - """ + """Represent the PostgreSQL TSTZRANGE type.""" __visit_name__ = "TSTZRANGE" diff --git a/lib/sqlalchemy/dialects/sqlite/pysqlite.py b/lib/sqlalchemy/dialects/sqlite/pysqlite.py index a8b234921..eb855016e 100644 --- a/lib/sqlalchemy/dialects/sqlite/pysqlite.py +++ b/lib/sqlalchemy/dialects/sqlite/pysqlite.py @@ -515,7 +515,9 @@ class SQLiteDialect_pysqlite(SQLiteDialect): dbapi_connection = connection dbapi_connection.create_function( - "regexp", 2, regexp, + "regexp", + 2, + regexp, ) fns = [set_regexp] diff --git a/lib/sqlalchemy/engine/base.py b/lib/sqlalchemy/engine/base.py index e6215540d..9a6bdd7f3 100644 --- a/lib/sqlalchemy/engine/base.py +++ b/lib/sqlalchemy/engine/base.py @@ -67,9 +67,7 @@ class Connection(Connectable): _dispatch=None, _has_events=None, ): - """Construct a new Connection. - - """ + """Construct a new Connection.""" self.engine = engine self.dialect = engine.dialect self.__branch_from = _branch_from @@ -347,7 +345,7 @@ class Connection(Connectable): return c def get_execution_options(self): - """ Get the non-SQL options which will take effect during execution. + """Get the non-SQL options which will take effect during execution. .. versionadded:: 1.3 @@ -1234,7 +1232,11 @@ class Connection(Connectable): for fn in self.dispatch.before_execute: elem, event_multiparams, event_params = fn( - self, elem, event_multiparams, event_params, execution_options, + self, + elem, + event_multiparams, + event_params, + execution_options, ) if event_multiparams: @@ -2124,9 +2126,7 @@ class Transaction(object): assert not self.is_active def rollback(self): - """Roll back this :class:`.Transaction`. - - """ + """Roll back this :class:`.Transaction`.""" try: self._do_rollback() finally: @@ -2618,7 +2618,7 @@ class Engine(Connectable, log.Identified): return self._option_cls(self, opt) def get_execution_options(self): - """ Get the non-SQL options which will take effect during execution. + """Get the non-SQL options which will take effect during execution. .. versionadded: 1.3 diff --git a/lib/sqlalchemy/engine/cursor.py b/lib/sqlalchemy/engine/cursor.py index 43afa3628..6c4a756c9 100644 --- a/lib/sqlalchemy/engine/cursor.py +++ b/lib/sqlalchemy/engine/cursor.py @@ -1034,7 +1034,8 @@ class BufferedRowCursorFetchStrategy(CursorFetchStrategy): @classmethod def create(cls, result): return BufferedRowCursorFetchStrategy( - result.cursor, result.context.execution_options, + result.cursor, + result.context.execution_options, ) def _buffer_rows(self, result, dbapi_cursor): @@ -1204,9 +1205,7 @@ _NO_RESULT_METADATA = _NoResultMetaData() class BaseCursorResult(object): - """Base class for database result objects. - - """ + """Base class for database result objects.""" out_parameters = None _metadata = None diff --git a/lib/sqlalchemy/engine/interfaces.py b/lib/sqlalchemy/engine/interfaces.py index e0e4a9a83..27de5aaaf 100644 --- a/lib/sqlalchemy/engine/interfaces.py +++ b/lib/sqlalchemy/engine/interfaces.py @@ -530,7 +530,7 @@ class Dialect(object): :param dbapi_connection: a DBAPI connection, typically proxied within a :class:`.ConnectionFairy`. - """ + """ raise NotImplementedError() @@ -541,7 +541,7 @@ class Dialect(object): :param dbapi_connection: a DBAPI connection, typically proxied within a :class:`.ConnectionFairy`. - """ + """ raise NotImplementedError() diff --git a/lib/sqlalchemy/engine/reflection.py b/lib/sqlalchemy/engine/reflection.py index 198b5e568..812f7ceec 100644 --- a/lib/sqlalchemy/engine/reflection.py +++ b/lib/sqlalchemy/engine/reflection.py @@ -230,8 +230,7 @@ class Inspector(object): return self.dialect.default_schema_name def get_schema_names(self): - """Return all schema names. - """ + """Return all schema names.""" if hasattr(self.dialect, "get_schema_names"): with self._operation_context() as conn: diff --git a/lib/sqlalchemy/engine/result.py b/lib/sqlalchemy/engine/result.py index 56abca9a9..8b9b413c4 100644 --- a/lib/sqlalchemy/engine/result.py +++ b/lib/sqlalchemy/engine/result.py @@ -167,7 +167,10 @@ class SimpleResultMetaData(ResultMetaData): if extra: recs_names = [ - ((name,) + extras, (index, name, extras),) + ( + (name,) + extras, + (index, name, extras), + ) for index, (name, extras) in enumerate(zip(self._keys, extra)) ] else: @@ -407,7 +410,10 @@ class ResultInternal(InPlaceGenerative): rows = [ made_row for made_row, sig_row in [ - (made_row, strategy(made_row) if strategy else made_row,) + ( + made_row, + strategy(made_row) if strategy else made_row, + ) for made_row in made_rows ] if sig_row not in uniques and not uniques.add(sig_row) @@ -543,7 +549,10 @@ class ResultInternal(InPlaceGenerative): return manyrows def _only_one_row( - self, raise_for_second_row, raise_for_none, scalar, + self, + raise_for_second_row, + raise_for_none, + scalar, ): onerow = self._fetchone_impl @@ -1400,10 +1409,7 @@ class MappingResult(FilterResult): def columns(self, *col_expressions): # type: (*object) -> MappingResult - r"""Establish the columns that should be returned in each row. - - - """ + r"""Establish the columns that should be returned in each row.""" return self._column_slices(col_expressions) def partitions(self, size=None): diff --git a/lib/sqlalchemy/engine/url.py b/lib/sqlalchemy/engine/url.py index 6d2f4aa24..58f59642c 100644 --- a/lib/sqlalchemy/engine/url.py +++ b/lib/sqlalchemy/engine/url.py @@ -140,7 +140,7 @@ class URL( :class:`_engine.URL`, use the :meth:`_engine.URL.set` and :meth:`_engine.URL.update_query` methods. - """ + """ return cls( cls._assert_str(drivername, "drivername"), @@ -205,7 +205,9 @@ class URL( return util.immutabledict( { - _assert_str(key): _assert_value(value,) + _assert_str(key): _assert_value( + value, + ) for key, value in dict_items } ) diff --git a/lib/sqlalchemy/event/api.py b/lib/sqlalchemy/event/api.py index b36c448ce..cd09235c3 100644 --- a/lib/sqlalchemy/event/api.py +++ b/lib/sqlalchemy/event/api.py @@ -196,8 +196,6 @@ def remove(target, identifier, fn): def contains(target, identifier, fn): - """Return True if the given target/ident/fn is set up to listen. - - """ + """Return True if the given target/ident/fn is set up to listen.""" return _event_key(target, identifier, fn).contains() diff --git a/lib/sqlalchemy/event/attr.py b/lib/sqlalchemy/event/attr.py index abb264f98..baa3cd28a 100644 --- a/lib/sqlalchemy/event/attr.py +++ b/lib/sqlalchemy/event/attr.py @@ -379,7 +379,7 @@ class _ListenerCollection(_CompoundListener): def _update(self, other, only_propagate=True): """Populate from the listeners in another :class:`_Dispatch` - object.""" + object.""" existing_listeners = self.listeners existing_listener_set = set(existing_listeners) diff --git a/lib/sqlalchemy/event/base.py b/lib/sqlalchemy/event/base.py index c78080738..daa6f9aea 100644 --- a/lib/sqlalchemy/event/base.py +++ b/lib/sqlalchemy/event/base.py @@ -142,7 +142,7 @@ class _Dispatch(object): def _update(self, other, only_propagate=True): """Populate from the listeners in another :class:`_Dispatch` - object.""" + object.""" for ls in other._event_descriptors: if isinstance(ls, _EmptyListener): continue diff --git a/lib/sqlalchemy/event/registry.py b/lib/sqlalchemy/event/registry.py index 144dd45dc..58680f356 100644 --- a/lib/sqlalchemy/event/registry.py +++ b/lib/sqlalchemy/event/registry.py @@ -139,8 +139,7 @@ def _clear(owner, elements): class _EventKey(object): - """Represent :func:`.listen` arguments. - """ + """Represent :func:`.listen` arguments.""" __slots__ = ( "target", @@ -239,8 +238,7 @@ class _EventKey(object): collection.remove(self.with_wrapper(listener_fn)) def contains(self): - """Return True if this event key is registered to listen. - """ + """Return True if this event key is registered to listen.""" return self._key in _key_to_collection def base_listen( diff --git a/lib/sqlalchemy/exc.py b/lib/sqlalchemy/exc.py index b80bf9b01..7e4a3f53e 100644 --- a/lib/sqlalchemy/exc.py +++ b/lib/sqlalchemy/exc.py @@ -35,7 +35,11 @@ class SQLAlchemyError(Exception): else: return ( "(Background on this error at: " - "http://sqlalche.me/e/%s/%s)" % (_version_token, self.code,) + "http://sqlalche.me/e/%s/%s)" + % ( + _version_token, + self.code, + ) ) def _message(self, as_unicode=compat.py3k): diff --git a/lib/sqlalchemy/ext/associationproxy.py b/lib/sqlalchemy/ext/associationproxy.py index 3ea77a952..a2c6b596f 100644 --- a/lib/sqlalchemy/ext/associationproxy.py +++ b/lib/sqlalchemy/ext/associationproxy.py @@ -840,8 +840,7 @@ class AmbiguousAssociationProxyInstance(AssociationProxyInstance): class ObjectAssociationProxyInstance(AssociationProxyInstance): - """an :class:`.AssociationProxyInstance` that has an object as a target. - """ + """an :class:`.AssociationProxyInstance` that has an object as a target.""" _target_is_object = True _is_canonical = True diff --git a/lib/sqlalchemy/ext/asyncio/engine.py b/lib/sqlalchemy/ext/asyncio/engine.py index 619cf8508..4a92fb1f2 100644 --- a/lib/sqlalchemy/ext/asyncio/engine.py +++ b/lib/sqlalchemy/ext/asyncio/engine.py @@ -85,16 +85,12 @@ class AsyncConnection(StartableContext): return self.sync_connection def begin(self) -> "AsyncTransaction": - """Begin a transaction prior to autobegin occurring. - - """ + """Begin a transaction prior to autobegin occurring.""" self._sync_connection() return AsyncTransaction(self) def begin_nested(self) -> "AsyncTransaction": - """Begin a nested transaction and return a transaction handle. - - """ + """Begin a nested transaction and return a transaction handle.""" self._sync_connection() return AsyncTransaction(self, nested=True) @@ -154,7 +150,10 @@ class AsyncConnection(StartableContext): conn = self._sync_connection() result = await greenlet_spawn( - conn.exec_driver_sql, statement, parameters, execution_options, + conn.exec_driver_sql, + statement, + parameters, + execution_options, ) if result.context._is_server_side: raise async_exc.AsyncMethodRequired( @@ -230,7 +229,10 @@ class AsyncConnection(StartableContext): conn = self._sync_connection() result = await greenlet_spawn( - conn._execute_20, statement, parameters, execution_options, + conn._execute_20, + statement, + parameters, + execution_options, ) if result.context._is_server_side: raise async_exc.AsyncMethodRequired( @@ -261,7 +263,7 @@ class AsyncConnection(StartableContext): return result.scalar() async def run_sync(self, fn: Callable, *arg, **kw) -> Any: - """"Invoke the given sync callable passing self as the first argument. + """Invoke the given sync callable passing self as the first argument. This method maintains the asyncio event loop all the way through to the database connection by running the given callable in a @@ -418,9 +420,7 @@ class AsyncTransaction(StartableContext): await greenlet_spawn(self._sync_transaction().close) async def rollback(self): - """Roll back this :class:`.Transaction`. - - """ + """Roll back this :class:`.Transaction`.""" await greenlet_spawn(self._sync_transaction().rollback) async def commit(self): diff --git a/lib/sqlalchemy/ext/asyncio/result.py b/lib/sqlalchemy/ext/asyncio/result.py index 52b40acba..7f8a707d5 100644 --- a/lib/sqlalchemy/ext/asyncio/result.py +++ b/lib/sqlalchemy/ext/asyncio/result.py @@ -553,10 +553,7 @@ class AsyncMappingResult(FilterResult): def columns(self, *col_expressions): # type: (*object) -> AsyncMappingResult - r"""Establish the columns that should be returned in each row. - - - """ + r"""Establish the columns that should be returned in each row.""" return self._column_slices(col_expressions) async def partitions(self, size=None): diff --git a/lib/sqlalchemy/ext/asyncio/session.py b/lib/sqlalchemy/ext/asyncio/session.py index 167301780..cb06aa26d 100644 --- a/lib/sqlalchemy/ext/asyncio/session.py +++ b/lib/sqlalchemy/ext/asyncio/session.py @@ -269,9 +269,7 @@ class AsyncSessionTransaction(StartableContext): return self.sync_transaction async def rollback(self): - """Roll back this :class:`_asyncio.AsyncTransaction`. - - """ + """Roll back this :class:`_asyncio.AsyncTransaction`.""" await greenlet_spawn(self._sync_transaction().rollback) async def commit(self): diff --git a/lib/sqlalchemy/ext/baked.py b/lib/sqlalchemy/ext/baked.py index 288677387..8a2023e96 100644 --- a/lib/sqlalchemy/ext/baked.py +++ b/lib/sqlalchemy/ext/baked.py @@ -173,8 +173,7 @@ class BakedQuery(object): return self._cache_key + (session._query_cls,) def _with_lazyload_options(self, options, effective_path, cache_path=None): - """Cloning version of _add_lazyload_options. - """ + """Cloning version of _add_lazyload_options.""" q = self._clone() q._add_lazyload_options(options, effective_path, cache_path=cache_path) return q diff --git a/lib/sqlalchemy/ext/hybrid.py b/lib/sqlalchemy/ext/hybrid.py index 75bb028f0..83562502a 100644 --- a/lib/sqlalchemy/ext/hybrid.py +++ b/lib/sqlalchemy/ext/hybrid.py @@ -950,7 +950,7 @@ class hybrid_property(interfaces.InspectionAttrInfo): :ref:`hybrid_reuse_subclass` - """ + """ return self def getter(self, fget): diff --git a/lib/sqlalchemy/ext/orderinglist.py b/lib/sqlalchemy/ext/orderinglist.py index 7b6b77997..03ea096e7 100644 --- a/lib/sqlalchemy/ext/orderinglist.py +++ b/lib/sqlalchemy/ext/orderinglist.py @@ -376,7 +376,7 @@ class OrderingList(list): def _reconstitute(cls, dict_, items): - """ Reconstitute an :class:`.OrderingList`. + """Reconstitute an :class:`.OrderingList`. This is the adjoint to :meth:`.OrderingList.__reduce__`. It is used for unpickling :class:`.OrderingList` objects. diff --git a/lib/sqlalchemy/inspection.py b/lib/sqlalchemy/inspection.py index 270f189be..4d9ee30c4 100644 --- a/lib/sqlalchemy/inspection.py +++ b/lib/sqlalchemy/inspection.py @@ -54,7 +54,7 @@ def inspect(subject, raiseerr=True): :class:`sqlalchemy.exc.NoInspectionAvailable` is raised. If ``False``, ``None`` is returned. - """ + """ type_ = type(subject) for cls in type_.__mro__: if cls in _registrars: diff --git a/lib/sqlalchemy/orm/__init__.py b/lib/sqlalchemy/orm/__init__.py index 7f2c61a05..e36797d47 100644 --- a/lib/sqlalchemy/orm/__init__.py +++ b/lib/sqlalchemy/orm/__init__.py @@ -119,9 +119,7 @@ relationship = public_factory(RelationshipProperty, ".orm.relationship") @_sa_util.deprecated_20("relation", "Please use :func:`.relationship`.") def relation(*arg, **kw): - """A synonym for :func:`relationship`. - - """ + """A synonym for :func:`relationship`.""" return relationship(*arg, **kw) diff --git a/lib/sqlalchemy/orm/attributes.py b/lib/sqlalchemy/orm/attributes.py index 07b147f10..c7ef97c6c 100644 --- a/lib/sqlalchemy/orm/attributes.py +++ b/lib/sqlalchemy/orm/attributes.py @@ -968,9 +968,9 @@ class ScalarAttributeImpl(AttributeImpl): class ScalarObjectAttributeImpl(ScalarAttributeImpl): """represents a scalar-holding InstrumentedAttribute, - where the target object is also instrumented. + where the target object is also instrumented. - Adds events to delete/set operations. + Adds events to delete/set operations. """ @@ -1065,9 +1065,7 @@ class ScalarObjectAttributeImpl(ScalarAttributeImpl): check_old=None, pop=False, ): - """Set a value on the given InstanceState. - - """ + """Set a value on the given InstanceState.""" if self.dispatch._active_history: old = self.get( state, diff --git a/lib/sqlalchemy/orm/context.py b/lib/sqlalchemy/orm/context.py index c24e04aa5..5e9cf9cce 100644 --- a/lib/sqlalchemy/orm/context.py +++ b/lib/sqlalchemy/orm/context.py @@ -1223,7 +1223,14 @@ class ORMSelectCompileState(ORMCompileState, SelectState): # figure out the final "left" and "right" sides and create an # ORMJoin to add to our _from_obj tuple self._join_left_to_right( - left, right, onclause, prop, False, False, isouter, full, + left, + right, + onclause, + prop, + False, + False, + isouter, + full, ) def _legacy_join(self, args): @@ -1822,7 +1829,8 @@ class ORMSelectCompileState(ORMCompileState, SelectState): self._mapper_loads_polymorphically_with( right_mapper, sql_util.ColumnAdapter( - right_mapper.selectable, right_mapper._equivalent_columns, + right_mapper.selectable, + right_mapper._equivalent_columns, ), ) # if the onclause is a ClauseElement, adapt it with any @@ -2538,7 +2546,11 @@ class _ORMColumnEntity(_ColumnEntity): ) def __init__( - self, compile_state, column, parententity, parent_bundle=None, + self, + compile_state, + column, + parententity, + parent_bundle=None, ): annotations = column._annotations diff --git a/lib/sqlalchemy/orm/decl_api.py b/lib/sqlalchemy/orm/decl_api.py index 70fffa295..4d9766204 100644 --- a/lib/sqlalchemy/orm/decl_api.py +++ b/lib/sqlalchemy/orm/decl_api.py @@ -375,7 +375,12 @@ def declarative_base( metadata=metadata, class_registry=class_registry, constructor=constructor, - ).generate_base(mapper=mapper, cls=cls, name=name, metaclass=metaclass,) + ).generate_base( + mapper=mapper, + cls=cls, + name=name, + metaclass=metaclass, + ) class registry(object): @@ -458,7 +463,11 @@ class registry(object): clsregistry.remove_class(cls.__name__, cls, self._class_registry) def generate_base( - self, mapper=None, cls=object, name="Base", metaclass=DeclarativeMeta, + self, + mapper=None, + cls=object, + name="Base", + metaclass=DeclarativeMeta, ): """Generate a declarative base class. diff --git a/lib/sqlalchemy/orm/decl_base.py b/lib/sqlalchemy/orm/decl_base.py index 0e0c79b1f..0e89e729f 100644 --- a/lib/sqlalchemy/orm/decl_base.py +++ b/lib/sqlalchemy/orm/decl_base.py @@ -203,7 +203,11 @@ class _ImperativeMapperConfig(_MapperConfig): __slots__ = ("dict_", "local_table", "inherits") def __init__( - self, registry, cls_, table, mapper_kw, + self, + registry, + cls_, + table, + mapper_kw, ): super(_ImperativeMapperConfig, self).__init__(registry, cls_) @@ -223,7 +227,8 @@ class _ImperativeMapperConfig(_MapperConfig): mapper_cls = mapper return self.set_cls_attribute( - "__mapper__", mapper_cls(self.cls, self.local_table, **mapper_kw), + "__mapper__", + mapper_cls(self.cls, self.local_table, **mapper_kw), ) def _setup_inheritance(self, mapper_kw): @@ -274,7 +279,12 @@ class _ClassScanMapperConfig(_MapperConfig): ) def __init__( - self, registry, cls_, dict_, table, mapper_kw, + self, + registry, + cls_, + dict_, + table, + mapper_kw, ): super(_ClassScanMapperConfig, self).__init__(registry, cls_) diff --git a/lib/sqlalchemy/orm/descriptor_props.py b/lib/sqlalchemy/orm/descriptor_props.py index c2efa24a1..713891d91 100644 --- a/lib/sqlalchemy/orm/descriptor_props.py +++ b/lib/sqlalchemy/orm/descriptor_props.py @@ -26,7 +26,7 @@ from ..sql import expression class DescriptorProperty(MapperProperty): """:class:`.MapperProperty` which proxies access to a - user-defined descriptor.""" + user-defined descriptor.""" doc = None diff --git a/lib/sqlalchemy/orm/dynamic.py b/lib/sqlalchemy/orm/dynamic.py index 48161a256..4426041e3 100644 --- a/lib/sqlalchemy/orm/dynamic.py +++ b/lib/sqlalchemy/orm/dynamic.py @@ -487,12 +487,15 @@ class AppenderQuery(Generative): iterator = ( (item,) for item in self.attr._get_collection_history( - state, attributes.PASSIVE_NO_INITIALIZE, + state, + attributes.PASSIVE_NO_INITIALIZE, ).added_items ) row_metadata = _result.SimpleResultMetaData( - (self.mapper.class_.__name__,), [], _unique_filters=[id], + (self.mapper.class_.__name__,), + [], + _unique_filters=[id], ) return _result.IteratorResult(row_metadata, iterator).scalars() diff --git a/lib/sqlalchemy/orm/loading.py b/lib/sqlalchemy/orm/loading.py index a7dd1c547..ecb704a04 100644 --- a/lib/sqlalchemy/orm/loading.py +++ b/lib/sqlalchemy/orm/loading.py @@ -639,7 +639,7 @@ def _instance_processor( _polymorphic_from=None, ): """Produce a mapper level row processor callable - which processes rows into mapped instances.""" + which processes rows into mapped instances.""" # note that this method, most of which exists in a closure # called _instance(), resists being broken out, as @@ -1253,9 +1253,7 @@ def _decorate_polymorphic_switch( class PostLoad(object): - """Track loaders and states for "post load" operations. - - """ + """Track loaders and states for "post load" operations.""" __slots__ = "loaders", "states", "load_keys" diff --git a/lib/sqlalchemy/orm/mapper.py b/lib/sqlalchemy/orm/mapper.py index 296ddf385..7b94bfa87 100644 --- a/lib/sqlalchemy/orm/mapper.py +++ b/lib/sqlalchemy/orm/mapper.py @@ -1275,8 +1275,7 @@ class Mapper( @classmethod def _configure_all(cls): - """Class-level path to the :func:`.configure_mappers` call. - """ + """Class-level path to the :func:`.configure_mappers` call.""" configure_mappers() def dispose(self): @@ -1799,7 +1798,7 @@ class Mapper( @util.preload_module("sqlalchemy.orm.descriptor_props") def _property_from_column(self, key, prop): """generate/update a :class:`.ColumnProperty` given a - :class:`_schema.Column` object. """ + :class:`_schema.Column` object.""" descriptor_props = util.preloaded.orm_descriptor_props # we were passed a Column or a list of Columns; # generate a properties.ColumnProperty @@ -1983,8 +1982,7 @@ class Mapper( return key in self._props def get_property(self, key, _configure_mappers=True): - """return a MapperProperty associated with the given key. - """ + """return a MapperProperty associated with the given key.""" if _configure_mappers and Mapper._new_mappers: configure_mappers() diff --git a/lib/sqlalchemy/orm/persistence.py b/lib/sqlalchemy/orm/persistence.py index d05381c1d..fa126a279 100644 --- a/lib/sqlalchemy/orm/persistence.py +++ b/lib/sqlalchemy/orm/persistence.py @@ -1179,7 +1179,8 @@ def _emit_insert_statements( c.returned_defaults_rows or (), ): for pk, col in zip( - inserted_primary_key, mapper._pks_by_table[table], + inserted_primary_key, + mapper._pks_by_table[table], ): prop = mapper_rec._columntoproperty[col] if state_dict.get(prop.key) is None: @@ -2236,7 +2237,8 @@ class BulkORMUpdate(UpdateDMLState, BulkUDCompileState): session.identity_map[identity_key] for identity_key in [ target_mapper.identity_key_from_primary_key( - list(primary_key), identity_token=identity_token, + list(primary_key), + identity_token=identity_token, ) for primary_key, identity_token in [ (row[0:-1], row[-1]) for row in matched_rows @@ -2337,7 +2339,8 @@ class BulkORMDelete(DeleteDMLState, BulkUDCompileState): # TODO: inline this and call remove_newly_deleted # once identity_key = target_mapper.identity_key_from_primary_key( - list(primary_key), identity_token=identity_token, + list(primary_key), + identity_token=identity_token, ) if identity_key in session.identity_map: session._remove_newly_deleted( diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py index e7bfc25b7..0e7fd2fc3 100644 --- a/lib/sqlalchemy/orm/query.py +++ b/lib/sqlalchemy/orm/query.py @@ -435,7 +435,10 @@ class Query( return stmt def subquery( - self, name=None, with_labels=False, reduce_columns=False, + self, + name=None, + with_labels=False, + reduce_columns=False, ): """Return the full SELECT statement represented by this :class:`_query.Query`, embedded within an @@ -1496,7 +1499,7 @@ class Query( return fn(self) def get_execution_options(self): - """ Get the non-SQL options which will take effect during execution. + """Get the non-SQL options which will take effect during execution. .. versionadded:: 1.3 @@ -1508,7 +1511,7 @@ class Query( @_generative def execution_options(self, **kwargs): - """ Set non-SQL options which take effect during execution. + """Set non-SQL options which take effect during execution. Options allowed here include all of those accepted by :meth:`_engine.Connection.execution_options`, as well as a series @@ -3030,7 +3033,9 @@ class Query( """ - bulk_del = BulkDelete(self,) + bulk_del = BulkDelete( + self, + ) if self.dispatch.before_compile_delete: for fn in self.dispatch.before_compile_delete: new_query = fn(bulk_del.query, bulk_del) diff --git a/lib/sqlalchemy/orm/relationships.py b/lib/sqlalchemy/orm/relationships.py index cd1502073..13611f2bb 100644 --- a/lib/sqlalchemy/orm/relationships.py +++ b/lib/sqlalchemy/orm/relationships.py @@ -3636,9 +3636,7 @@ class JoinCondition(object): class _ColInAnnotations(object): - """Seralizable object that tests for a name in c._annotations. - - """ + """Seralizable object that tests for a name in c._annotations.""" __slots__ = ("name",) diff --git a/lib/sqlalchemy/orm/session.py b/lib/sqlalchemy/orm/session.py index bebe015f7..e32e05510 100644 --- a/lib/sqlalchemy/orm/session.py +++ b/lib/sqlalchemy/orm/session.py @@ -47,7 +47,7 @@ _sessions = weakref.WeakValueDictionary() def _state_session(state): """Given an :class:`.InstanceState`, return the :class:`.Session` - associated, if any. + associated, if any. """ if state.session_id: try: @@ -404,7 +404,11 @@ class SessionTransaction(object): _rollback_exception = None def __init__( - self, session, parent=None, nested=False, autobegin=False, + self, + session, + parent=None, + nested=False, + autobegin=False, ): self.session = session self._connections = {} @@ -1865,7 +1869,8 @@ class Session(_SessionClassMethods): except sa_exc.NoInspectionAvailable as err: if isinstance(mapper, type): util.raise_( - exc.UnmappedClassError(mapper), replace_context=err, + exc.UnmappedClassError(mapper), + replace_context=err, ) else: raise @@ -2098,7 +2103,8 @@ class Session(_SessionClassMethods): state = attributes.instance_state(instance) except exc.NO_STATE as err: util.raise_( - exc.UnmappedInstanceError(instance), replace_context=err, + exc.UnmappedInstanceError(instance), + replace_context=err, ) self._expire_state(state, attribute_names) @@ -2204,7 +2210,8 @@ class Session(_SessionClassMethods): state = attributes.instance_state(instance) except exc.NO_STATE as err: util.raise_( - exc.UnmappedInstanceError(instance), replace_context=err, + exc.UnmappedInstanceError(instance), + replace_context=err, ) self._expire_state(state, attribute_names) @@ -2242,7 +2249,8 @@ class Session(_SessionClassMethods): state = attributes.instance_state(instance) except exc.NO_STATE as err: util.raise_( - exc.UnmappedInstanceError(instance), replace_context=err, + exc.UnmappedInstanceError(instance), + replace_context=err, ) if state.session_id is not self.hash_key: raise sa_exc.InvalidRequestError( @@ -2396,7 +2404,8 @@ class Session(_SessionClassMethods): state = attributes.instance_state(instance) except exc.NO_STATE as err: util.raise_( - exc.UnmappedInstanceError(instance), replace_context=err, + exc.UnmappedInstanceError(instance), + replace_context=err, ) self._save_or_update_state(state) @@ -2433,7 +2442,8 @@ class Session(_SessionClassMethods): state = attributes.instance_state(instance) except exc.NO_STATE as err: util.raise_( - exc.UnmappedInstanceError(instance), replace_context=err, + exc.UnmappedInstanceError(instance), + replace_context=err, ) self._delete_impl(state, instance, head=True) @@ -2663,7 +2673,10 @@ class Session(_SessionClassMethods): if execution_options: statement = statement.execution_options(**execution_options) return db_load_fn( - self, statement, primary_key_identity, load_options=load_options, + self, + statement, + primary_key_identity, + load_options=load_options, ) def merge(self, instance, load=True): @@ -3060,7 +3073,8 @@ class Session(_SessionClassMethods): state = attributes.instance_state(instance) except exc.NO_STATE as err: util.raise_( - exc.UnmappedInstanceError(instance), replace_context=err, + exc.UnmappedInstanceError(instance), + replace_context=err, ) return self._contains_state(state) @@ -3159,7 +3173,8 @@ class Session(_SessionClassMethods): except exc.NO_STATE as err: util.raise_( - exc.UnmappedInstanceError(o), replace_context=err, + exc.UnmappedInstanceError(o), + replace_context=err, ) objset.add(state) else: @@ -4062,7 +4077,8 @@ def object_session(instance): state = attributes.instance_state(instance) except exc.NO_STATE as err: util.raise_( - exc.UnmappedInstanceError(instance), replace_context=err, + exc.UnmappedInstanceError(instance), + replace_context=err, ) else: return _state_session(state) diff --git a/lib/sqlalchemy/orm/state.py b/lib/sqlalchemy/orm/state.py index 233283497..b139d5933 100644 --- a/lib/sqlalchemy/orm/state.py +++ b/lib/sqlalchemy/orm/state.py @@ -212,7 +212,7 @@ class InstanceState(interfaces.InspectionAttrInfo): :ref:`session_object_states` - """ + """ return self.key is not None and self._attached and not self._deleted @property @@ -533,7 +533,7 @@ class InstanceState(interfaces.InspectionAttrInfo): def _reset(self, dict_, key): """Remove the given attribute and any - callables associated with it.""" + callables associated with it.""" old = dict_.pop(key, None) if old is not None and self.manager[key].impl.collection: diff --git a/lib/sqlalchemy/orm/strategies.py b/lib/sqlalchemy/orm/strategies.py index 325bd4dc1..900691688 100644 --- a/lib/sqlalchemy/orm/strategies.py +++ b/lib/sqlalchemy/orm/strategies.py @@ -1455,7 +1455,12 @@ class SubqueryLoader(PostLoader): self._load() def _setup_query_from_rowproc( - self, context, path, entity, loadopt, adapter, + self, + context, + path, + entity, + loadopt, + adapter, ): compile_state = context.compile_state if ( @@ -1627,7 +1632,11 @@ class SubqueryLoader(PostLoader): return subq = self._setup_query_from_rowproc( - context, path, path[-1], loadopt, adapter, + context, + path, + path[-1], + loadopt, + adapter, ) if subq is None: @@ -1879,7 +1888,9 @@ class JoinedLoader(AbstractRelationshipLoader): prop.mapper, None ) path.set( - target_attributes, "user_defined_eager_row_processor", adapter, + target_attributes, + "user_defined_eager_row_processor", + adapter, ) return adapter diff --git a/lib/sqlalchemy/orm/util.py b/lib/sqlalchemy/orm/util.py index 170e4487e..f902014ef 100644 --- a/lib/sqlalchemy/orm/util.py +++ b/lib/sqlalchemy/orm/util.py @@ -487,7 +487,8 @@ class AliasedClass(object): if alias is None: alias = mapper._with_polymorphic_selectable._anonymous_fromclause( - name=name, flat=flat, + name=name, + flat=flat, ) self._aliased_insp = AliasedInsp( diff --git a/lib/sqlalchemy/schema.py b/lib/sqlalchemy/schema.py index fe4c60a2d..b83b5525f 100644 --- a/lib/sqlalchemy/schema.py +++ b/lib/sqlalchemy/schema.py @@ -48,8 +48,8 @@ from .sql.schema import DefaultGenerator # noqa from .sql.schema import FetchedValue # noqa from .sql.schema import ForeignKey # noqa from .sql.schema import ForeignKeyConstraint # noqa -from .sql.schema import Index # noqa from .sql.schema import Identity # noqa +from .sql.schema import Index # noqa from .sql.schema import MetaData # noqa from .sql.schema import PrimaryKeyConstraint # noqa from .sql.schema import SchemaItem # noqa diff --git a/lib/sqlalchemy/sql/base.py b/lib/sqlalchemy/sql/base.py index 67ee8c907..f9b5ce7e1 100644 --- a/lib/sqlalchemy/sql/base.py +++ b/lib/sqlalchemy/sql/base.py @@ -558,10 +558,7 @@ class _MetaOptions(type): class Options(util.with_metaclass(_MetaOptions)): - """A cacheable option dictionary with defaults. - - - """ + """A cacheable option dictionary with defaults.""" def __init__(self, **kw): self.__dict__.update(kw) @@ -635,7 +632,7 @@ class Options(util.with_metaclass(_MetaOptions)): def from_execution_options( cls, key, attrs, exec_options, statement_exec_options ): - """"process Options argument in terms of execution options. + """process Options argument in terms of execution options. e.g.:: @@ -706,9 +703,7 @@ class ExecutableOption(HasCopyInternals, HasCacheKey): __visit_name__ = "executable_option" def _clone(self): - """Create a shallow copy of this ExecutableOption. - - """ + """Create a shallow copy of this ExecutableOption.""" c = self.__class__.__new__(self.__class__) c.__dict__ = dict(self.__dict__) return c @@ -812,7 +807,7 @@ class Executable(Generative): @_generative def execution_options(self, **kw): - """ Set non-SQL options for the statement which take effect during + """Set non-SQL options for the statement which take effect during execution. Execution options can be set on a per-statement or @@ -858,7 +853,7 @@ class Executable(Generative): self._execution_options = self._execution_options.union(kw) def get_execution_options(self): - """ Get the non-SQL options which will take effect during execution. + """Get the non-SQL options which will take effect during execution. .. versionadded:: 1.3 @@ -877,9 +872,7 @@ class Executable(Generative): ":class:`.Session`.", ) def execute(self, *multiparams, **params): - """Compile and execute this :class:`.Executable`. - - """ + """Compile and execute this :class:`.Executable`.""" e = self.bind if e is None: label = getattr(self, "description", self.__class__.__name__) @@ -1388,18 +1381,18 @@ class DedupeColumnCollection(ColumnCollection): def replace(self, column): """add the given column to this collection, removing unaliased - versions of this column as well as existing columns with the - same key. + versions of this column as well as existing columns with the + same key. - e.g.:: + e.g.:: - t = Table('sometable', metadata, Column('col1', Integer)) - t.columns.replace(Column('col1', Integer, key='columnone')) + t = Table('sometable', metadata, Column('col1', Integer)) + t.columns.replace(Column('col1', Integer, key='columnone')) - will remove the original 'col1' from the collection, and add - the new column under the name 'columnname'. + will remove the original 'col1' from the collection, and add + the new column under the name 'columnname'. - Used by schema.Column to override columns during table reflection. + Used by schema.Column to override columns during table reflection. """ diff --git a/lib/sqlalchemy/sql/coercions.py b/lib/sqlalchemy/sql/coercions.py index 154564a08..558ced8bd 100644 --- a/lib/sqlalchemy/sql/coercions.py +++ b/lib/sqlalchemy/sql/coercions.py @@ -37,9 +37,13 @@ def _is_literal(element): """ - return not isinstance( - element, (Visitable, schema.SchemaEventTarget), - ) and not hasattr(element, "__clause_element__") + return ( + not isinstance( + element, + (Visitable, schema.SchemaEventTarget), + ) + and not hasattr(element, "__clause_element__") + ) def _deep_is_literal(element): diff --git a/lib/sqlalchemy/sql/crud.py b/lib/sqlalchemy/sql/crud.py index 986f63aad..1c68d6450 100644 --- a/lib/sqlalchemy/sql/crud.py +++ b/lib/sqlalchemy/sql/crud.py @@ -719,7 +719,8 @@ def _append_param_update( ( c, compiler.preparer.format_column( - c, use_table=include_table, + c, + use_table=include_table, ), compiler.process(c.onupdate.arg.self_group(), **kw), ) @@ -733,7 +734,8 @@ def _append_param_update( ( c, compiler.preparer.format_column( - c, use_table=include_table, + c, + use_table=include_table, ), _create_update_prefetch_bind_param(compiler, c, **kw), ) diff --git a/lib/sqlalchemy/sql/ddl.py b/lib/sqlalchemy/sql/ddl.py index 67c11f6c7..5f3074cdc 100644 --- a/lib/sqlalchemy/sql/ddl.py +++ b/lib/sqlalchemy/sql/ddl.py @@ -985,7 +985,9 @@ class SchemaDropper(DDLBase): def sort_tables( - tables, skip_fn=None, extra_dependencies=None, + tables, + skip_fn=None, + extra_dependencies=None, ): """Sort a collection of :class:`_schema.Table` objects based on dependency. diff --git a/lib/sqlalchemy/sql/dml.py b/lib/sqlalchemy/sql/dml.py index fd2efc6f9..5ddc9ef82 100644 --- a/lib/sqlalchemy/sql/dml.py +++ b/lib/sqlalchemy/sql/dml.py @@ -193,9 +193,7 @@ class UpdateBase( Executable, ClauseElement, ): - """Form the base for ``INSERT``, ``UPDATE``, and ``DELETE`` statements. - - """ + """Form the base for ``INSERT``, ``UPDATE``, and ``DELETE`` statements.""" __visit_name__ = "update_base" @@ -435,7 +433,7 @@ class UpdateBase( :param dialect_name: defaults to ``*``, if specified as the name of a particular dialect, will apply these hints only when that dialect is in use. - """ + """ if selectable is None: selectable = self.table diff --git a/lib/sqlalchemy/sql/elements.py b/lib/sqlalchemy/sql/elements.py index 59f3fa86b..c8ae1e6b6 100644 --- a/lib/sqlalchemy/sql/elements.py +++ b/lib/sqlalchemy/sql/elements.py @@ -3526,7 +3526,10 @@ class BinaryExpression(ColumnElement): ("operator", InternalTraversal.dp_operator), ("negate", InternalTraversal.dp_operator), ("modifiers", InternalTraversal.dp_plain_dict), - ("type", InternalTraversal.dp_type,), # affects JSON CAST operators + ( + "type", + InternalTraversal.dp_type, + ), # affects JSON CAST operators ] _is_implicitly_boolean = True @@ -3638,8 +3641,8 @@ class Slice(ColumnElement): class IndexExpression(BinaryExpression): - """Represent the class of expressions that are like an "index" operation. - """ + """Represent the class of expressions that are like an "index" + operation.""" pass diff --git a/lib/sqlalchemy/sql/lambdas.py b/lib/sqlalchemy/sql/lambdas.py index 7d52f97ee..676152781 100644 --- a/lib/sqlalchemy/sql/lambdas.py +++ b/lib/sqlalchemy/sql/lambdas.py @@ -604,7 +604,11 @@ class AnalyzedCode(object): # create trackers to catch those. analyzed_function = AnalyzedFunction( - self, lambda_element, None, lambda_kw, fn, + self, + lambda_element, + None, + lambda_kw, + fn, ) closure_trackers = self.closure_trackers @@ -781,7 +785,12 @@ class AnalyzedFunction(object): ) def __init__( - self, analyzed_code, lambda_element, apply_propagate_attrs, kw, fn, + self, + analyzed_code, + lambda_element, + apply_propagate_attrs, + kw, + fn, ): self.analyzed_code = analyzed_code self.fn = fn diff --git a/lib/sqlalchemy/sql/schema.py b/lib/sqlalchemy/sql/schema.py index 496f8d9fb..e96da0e24 100644 --- a/lib/sqlalchemy/sql/schema.py +++ b/lib/sqlalchemy/sql/schema.py @@ -830,9 +830,7 @@ class Table(DialectKWArgs, SchemaItem, TableClause): ":meth:`_reflection.Inspector.has_table`.", ) def exists(self, bind=None): - """Return True if this table exists. - - """ + """Return True if this table exists.""" if bind is None: bind = _bind_or_error(self) @@ -3634,10 +3632,14 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint): if col.autoincrement is True: _validate_autoinc(col, True) return col - elif col.autoincrement in ( - "auto", - "ignore_fk", - ) and _validate_autoinc(col, False): + elif ( + col.autoincrement + in ( + "auto", + "ignore_fk", + ) + and _validate_autoinc(col, False) + ): return col else: diff --git a/lib/sqlalchemy/sql/sqltypes.py b/lib/sqlalchemy/sql/sqltypes.py index e2edf20b5..45d4f0b7f 100644 --- a/lib/sqlalchemy/sql/sqltypes.py +++ b/lib/sqlalchemy/sql/sqltypes.py @@ -361,7 +361,10 @@ class String(Concatenable, TypeEngine): needs_isinstance = ( needs_convert and dialect.returns_unicode_strings - in (String.RETURNS_CONDITIONAL, String.RETURNS_UNICODE,) + in ( + String.RETURNS_CONDITIONAL, + String.RETURNS_UNICODE, + ) and self._expect_unicode != "force_nocheck" ) if needs_convert: @@ -2286,7 +2289,7 @@ class JSON(Indexable, TypeEngine): :attr:`.types.JSON.NULL` - """ + """ self.none_as_null = none_as_null class JSONElementType(TypeEngine): diff --git a/lib/sqlalchemy/sql/type_api.py b/lib/sqlalchemy/sql/type_api.py index 0da88dc54..614b70a41 100644 --- a/lib/sqlalchemy/sql/type_api.py +++ b/lib/sqlalchemy/sql/type_api.py @@ -1156,10 +1156,7 @@ class TypeDecorator(SchemaEventTarget, TypeEngine): @util.memoized_property def _has_literal_processor(self): - """memoized boolean, check if process_literal_param is implemented. - - - """ + """memoized boolean, check if process_literal_param is implemented.""" return ( self.__class__.process_literal_param.__code__ diff --git a/lib/sqlalchemy/sql/util.py b/lib/sqlalchemy/sql/util.py index 264976cc8..96fa209fd 100644 --- a/lib/sqlalchemy/sql/util.py +++ b/lib/sqlalchemy/sql/util.py @@ -1011,8 +1011,7 @@ def _offset_or_limit_clause_asint_if_possible(clause): def _make_slice(limit_clause, offset_clause, start, stop): - """Compute LIMIT/OFFSET in terms of slice start/end - """ + """Compute LIMIT/OFFSET in terms of slice start/end""" # for calculated limit/offset, try to do the addition of # values to offset in Python, however if a SQL clause is present diff --git a/lib/sqlalchemy/testing/assertions.py b/lib/sqlalchemy/testing/assertions.py index c32b2749b..af168cd85 100644 --- a/lib/sqlalchemy/testing/assertions.py +++ b/lib/sqlalchemy/testing/assertions.py @@ -522,9 +522,12 @@ class ComparesTables(object): assert reflected_table.primary_key.columns[c.name] is not None def assert_types_base(self, c1, c2): - assert c1.type._compare_type_affinity(c2.type), ( - "On column %r, type '%s' doesn't correspond to type '%s'" - % (c1.name, c1.type, c2.type) + assert c1.type._compare_type_affinity( + c2.type + ), "On column %r, type '%s' doesn't correspond to type '%s'" % ( + c1.name, + c1.type, + c2.type, ) diff --git a/lib/sqlalchemy/testing/provision.py b/lib/sqlalchemy/testing/provision.py index 8bdad357c..18b856fb1 100644 --- a/lib/sqlalchemy/testing/provision.py +++ b/lib/sqlalchemy/testing/provision.py @@ -166,7 +166,9 @@ def generate_driver_url(url, driver, query_str): # type: (URL, str, str) -> URL backend = url.get_backend_name() - new_url = url.set(drivername="%s+%s" % (backend, driver),) + new_url = url.set( + drivername="%s+%s" % (backend, driver), + ) new_url = new_url.update_query_string(query_str) try: @@ -214,8 +216,7 @@ def drop_db(cfg, eng, ident): @register.init def update_db_opts(db_url, db_opts): - """Set database options (db_opts) for a test database that we created. - """ + """Set database options (db_opts) for a test database that we created.""" pass diff --git a/lib/sqlalchemy/testing/requirements.py b/lib/sqlalchemy/testing/requirements.py index 97413d32b..b7f0d0f59 100644 --- a/lib/sqlalchemy/testing/requirements.py +++ b/lib/sqlalchemy/testing/requirements.py @@ -67,7 +67,7 @@ class SuiteRequirements(Requirements): @property def on_update_cascade(self): - """"target database must support ON UPDATE..CASCADE behavior in + """target database must support ON UPDATE..CASCADE behavior in foreign keys.""" return exclusions.open() @@ -388,7 +388,7 @@ class SuiteRequirements(Requirements): @property def implements_get_lastrowid(self): - """"target dialect implements the executioncontext.get_lastrowid() + """target dialect implements the executioncontext.get_lastrowid() method without reliance on RETURNING. """ @@ -396,7 +396,7 @@ class SuiteRequirements(Requirements): @property def emulated_lastrowid(self): - """"target dialect retrieves cursor.lastrowid, or fetches + """target dialect retrieves cursor.lastrowid, or fetches from a database-side function after an insert() construct executes, within the get_lastrowid() method. @@ -408,7 +408,7 @@ class SuiteRequirements(Requirements): @property def emulated_lastrowid_even_with_sequences(self): - """"target dialect retrieves cursor.lastrowid or an equivalent + """target dialect retrieves cursor.lastrowid or an equivalent after an insert() construct executes, even if the table has a Sequence on it. @@ -417,7 +417,7 @@ class SuiteRequirements(Requirements): @property def dbapi_lastrowid(self): - """"target platform includes a 'lastrowid' accessor on the DBAPI + """target platform includes a 'lastrowid' accessor on the DBAPI cursor object. """ @@ -438,17 +438,16 @@ class SuiteRequirements(Requirements): @property def cross_schema_fk_reflection(self): - """target system must support reflection of inter-schema foreign keys - - """ + """target system must support reflection of inter-schema + foreign keys""" return exclusions.closed() @property def implicit_default_schema(self): """target system has a strong concept of 'default' schema that can - be referred to implicitly. + be referred to implicitly. - basically, PostgreSQL. + basically, PostgreSQL. """ return exclusions.closed() @@ -535,8 +534,8 @@ class SuiteRequirements(Requirements): @property def view_reflection(self): - """target database must support inspection of the full CREATE VIEW definition. - """ + """target database must support inspection of the full CREATE VIEW + definition.""" return self.views @property @@ -654,9 +653,7 @@ class SuiteRequirements(Requirements): @property def symbol_names_w_double_quote(self): - """Target driver can create tables with a name like 'some " table' - - """ + """Target driver can create tables with a name like 'some " table'""" return exclusions.open() @property @@ -804,7 +801,7 @@ class SuiteRequirements(Requirements): @property def json_array_indexes(self): - """"target platform supports numeric array indexes + """target platform supports numeric array indexes within a JSON structure""" return self.json_type diff --git a/lib/sqlalchemy/testing/suite/test_insert.py b/lib/sqlalchemy/testing/suite/test_insert.py index 7a7eac02f..da59d831f 100644 --- a/lib/sqlalchemy/testing/suite/test_insert.py +++ b/lib/sqlalchemy/testing/suite/test_insert.py @@ -42,7 +42,11 @@ class LastrowidTest(fixtures.TablesTest): def _assert_round_trip(self, table, conn): row = conn.execute(table.select()).first() eq_( - row, (conn.dialect.default_sequence_base, "some data",), + row, + ( + conn.dialect.default_sequence_base, + "some data", + ), ) def test_autoincrement_on_insert(self, connection): @@ -289,7 +293,11 @@ class ReturningTest(fixtures.TablesTest): def _assert_round_trip(self, table, conn): row = conn.execute(table.select()).first() eq_( - row, (conn.dialect.default_sequence_base, "some data",), + row, + ( + conn.dialect.default_sequence_base, + "some data", + ), ) @classmethod diff --git a/lib/sqlalchemy/testing/suite/test_reflection.py b/lib/sqlalchemy/testing/suite/test_reflection.py index 3c10a45f6..f728310d7 100644 --- a/lib/sqlalchemy/testing/suite/test_reflection.py +++ b/lib/sqlalchemy/testing/suite/test_reflection.py @@ -151,7 +151,10 @@ class QuotedNameArgumentTest(fixtures.TablesTest): Column("related_id", Integer), sa.PrimaryKeyConstraint("id", name="pk quote ' one"), sa.Index("ix quote ' one", "name"), - sa.UniqueConstraint("data", name="uq quote' one",), + sa.UniqueConstraint( + "data", + name="uq quote' one", + ), sa.ForeignKeyConstraint( ["id"], ["related.id"], name="fk quote ' one" ), @@ -170,7 +173,10 @@ class QuotedNameArgumentTest(fixtures.TablesTest): Column("related_id", Integer), sa.PrimaryKeyConstraint("id", name='pk quote " two'), sa.Index('ix quote " two', "name"), - sa.UniqueConstraint("data", name='uq quote" two',), + sa.UniqueConstraint( + "data", + name='uq quote" two', + ), sa.ForeignKeyConstraint( ["id"], ["related.id"], name='fk quote " two' ), @@ -1039,7 +1045,8 @@ class ComponentReflectionTest(fixtures.TablesTest): "Skipped unsupported reflection of expression-based index t_idx" ): eq_( - insp.get_indexes("t"), expected, + insp.get_indexes("t"), + expected, ) @testing.requires.index_reflects_included_columns @@ -1098,7 +1105,8 @@ class ComponentReflectionTest(fixtures.TablesTest): if testing.requires.index_reflects_included_columns.enabled: expected[0]["include_columns"] = [] eq_( - [idx for idx in indexes if idx["name"] == "user_tmp_ix"], expected, + [idx for idx in indexes if idx["name"] == "user_tmp_ix"], + expected, ) @testing.requires.unique_constraint_reflection @@ -1390,11 +1398,17 @@ class ComputedReflectionTest(fixtures.ComputedReflectionFixtureTest): ) if testing.requires.computed_columns_virtual.enabled: self.check_column( - data, "computed_virtual", "normal+2", False, + data, + "computed_virtual", + "normal+2", + False, ) if testing.requires.computed_columns_stored.enabled: self.check_column( - data, "computed_stored", "normal-42", True, + data, + "computed_stored", + "normal-42", + True, ) @testing.requires.schemas @@ -1414,11 +1428,17 @@ class ComputedReflectionTest(fixtures.ComputedReflectionFixtureTest): ) if testing.requires.computed_columns_virtual.enabled: self.check_column( - data, "computed_virtual", "normal/2", False, + data, + "computed_virtual", + "normal/2", + False, ) if testing.requires.computed_columns_stored.enabled: self.check_column( - data, "computed_stored", "normal*42", True, + data, + "computed_stored", + "normal*42", + True, ) diff --git a/lib/sqlalchemy/testing/suite/test_results.py b/lib/sqlalchemy/testing/suite/test_results.py index 1c1b20cf0..9484d41d0 100644 --- a/lib/sqlalchemy/testing/suite/test_results.py +++ b/lib/sqlalchemy/testing/suite/test_results.py @@ -408,7 +408,8 @@ class ServerSideCursorsTest( ) eq_( - result.fetchmany(5), [(i, "data%d" % i) for i in range(1, 6)], + result.fetchmany(5), + [(i, "data%d" % i) for i in range(1, 6)], ) eq_( result.fetchmany(10), diff --git a/lib/sqlalchemy/testing/suite/test_select.py b/lib/sqlalchemy/testing/suite/test_select.py index c199929a7..b0fb60c5f 100644 --- a/lib/sqlalchemy/testing/suite/test_select.py +++ b/lib/sqlalchemy/testing/suite/test_select.py @@ -1058,7 +1058,12 @@ class IdentityColumnTest(fixtures.TablesTest): Column( "id", Integer, - Identity(increment=-5, start=0, minvalue=-1000, maxvalue=0,), + Identity( + increment=-5, + start=0, + minvalue=-1000, + maxvalue=0, + ), primary_key=True, ), Column("desc", String(100)), @@ -1067,13 +1072,16 @@ class IdentityColumnTest(fixtures.TablesTest): @classmethod def insert_data(cls, connection): connection.execute( - cls.tables.tbl_a.insert(), [{"desc": "a"}, {"desc": "b"}], + cls.tables.tbl_a.insert(), + [{"desc": "a"}, {"desc": "b"}], ) connection.execute( - cls.tables.tbl_b.insert(), [{"desc": "a"}, {"desc": "b"}], + cls.tables.tbl_b.insert(), + [{"desc": "a"}, {"desc": "b"}], ) connection.execute( - cls.tables.tbl_b.insert(), [{"id": 42, "desc": "c"}], + cls.tables.tbl_b.insert(), + [{"id": 42, "desc": "c"}], ) def test_select_all(self, connection): @@ -1102,7 +1110,8 @@ class IdentityColumnTest(fixtures.TablesTest): def test_insert_always_error(self, connection): def fn(): connection.execute( - self.tables.tbl_a.insert(), [{"id": 200, "desc": "a"}], + self.tables.tbl_a.insert(), + [{"id": 200, "desc": "a"}], ) assert_raises((DatabaseError, ProgrammingError), fn) @@ -1204,7 +1213,8 @@ class IsOrIsNotDistinctFromTest(fixtures.TablesTest): tbl.select(tbl.c.col_a.is_distinct_from(tbl.c.col_b)) ).fetchall() eq_( - len(result), expected_row_count_for_is, + len(result), + expected_row_count_for_is, ) expected_row_count_for_isnot = ( @@ -1214,5 +1224,6 @@ class IsOrIsNotDistinctFromTest(fixtures.TablesTest): tbl.select(tbl.c.col_a.isnot_distinct_from(tbl.c.col_b)) ).fetchall() eq_( - len(result), expected_row_count_for_isnot, + len(result), + expected_row_count_for_isnot, ) diff --git a/lib/sqlalchemy/testing/suite/test_sequence.py b/lib/sqlalchemy/testing/suite/test_sequence.py index 5a1876bc5..de970da53 100644 --- a/lib/sqlalchemy/testing/suite/test_sequence.py +++ b/lib/sqlalchemy/testing/suite/test_sequence.py @@ -24,7 +24,12 @@ class SequenceTest(fixtures.TablesTest): Table( "seq_pk", metadata, - Column("id", Integer, Sequence("tab_id_seq"), primary_key=True,), + Column( + "id", + Integer, + Sequence("tab_id_seq"), + primary_key=True, + ), Column("data", String(50)), ) @@ -109,17 +114,21 @@ class HasSequenceTest(fixtures.TablesTest): "schema_seq", schema=config.test_schema, metadata=metadata ) Table( - "user_id_table", metadata, Column("id", Integer, primary_key=True), + "user_id_table", + metadata, + Column("id", Integer, primary_key=True), ) def test_has_sequence(self, connection): eq_( - inspect(connection).has_sequence("user_id_seq"), True, + inspect(connection).has_sequence("user_id_seq"), + True, ) def test_has_sequence_other_object(self, connection): eq_( - inspect(connection).has_sequence("user_id_table"), False, + inspect(connection).has_sequence("user_id_table"), + False, ) @testing.requires.schemas @@ -133,7 +142,8 @@ class HasSequenceTest(fixtures.TablesTest): def test_has_sequence_neg(self, connection): eq_( - inspect(connection).has_sequence("some_sequence"), False, + inspect(connection).has_sequence("some_sequence"), + False, ) @testing.requires.schemas @@ -157,7 +167,8 @@ class HasSequenceTest(fixtures.TablesTest): @testing.requires.schemas def test_has_sequence_remote_not_in_default(self, connection): eq_( - inspect(connection).has_sequence("schema_seq"), False, + inspect(connection).has_sequence("schema_seq"), + False, ) def test_get_sequence_names(self, connection): @@ -194,5 +205,6 @@ class HasSequenceTestEmpty(fixtures.TestBase): def test_get_sequence_names_no_sequence(self, connection): eq_( - inspect(connection).get_sequence_names(), [], + inspect(connection).get_sequence_names(), + [], ) diff --git a/lib/sqlalchemy/testing/suite/test_types.py b/lib/sqlalchemy/testing/suite/test_types.py index 8c6543700..da01aa484 100644 --- a/lib/sqlalchemy/testing/suite/test_types.py +++ b/lib/sqlalchemy/testing/suite/test_types.py @@ -621,9 +621,7 @@ class NumericTest(_LiteralRoundTripFixture, fixtures.TestBase): @testing.requires.precision_numerics_enotation_large def test_enotation_decimal_large(self): - """test exceedingly large decimals. - - """ + """test exceedingly large decimals.""" numbers = set( [ @@ -962,7 +960,8 @@ class JSONTest(_LiteralRoundTripFixture, fixtures.TablesTest): conn = connection conn.execute( - self.tables.data_table.insert(), {"name": "r1", "data": JSON.NULL}, + self.tables.data_table.insert(), + {"name": "r1", "data": JSON.NULL}, ) eq_( @@ -1158,13 +1157,18 @@ class JSONLegacyStringCastIndexTest( # "cannot extract array element from a non-array", which is # fixed in 9.4 but may exist in 9.3 self._test_index_criteria( - and_(name == "r4", cast(col[1], String) == '"two"',), "r4", + and_( + name == "r4", + cast(col[1], String) == '"two"', + ), + "r4", ) def test_string_cast_crit_mixed_path(self): col = self.tables.data_table.c["data"] self._test_index_criteria( - cast(col[("key3", 1, "six")], String) == '"seven"', "r3", + cast(col[("key3", 1, "six")], String) == '"seven"', + "r3", ) def test_string_cast_crit_string_path(self): @@ -1180,7 +1184,10 @@ class JSONLegacyStringCastIndexTest( col = self.tables.data_table.c["data"] self._test_index_criteria( - and_(name == "r6", cast(col["b"], String) == '"some value"',), + and_( + name == "r6", + cast(col["b"], String) == '"some value"', + ), "r6", ) diff --git a/lib/sqlalchemy/testing/warnings.py b/lib/sqlalchemy/testing/warnings.py index dbe22bb8d..5704cf2a6 100644 --- a/lib/sqlalchemy/testing/warnings.py +++ b/lib/sqlalchemy/testing/warnings.py @@ -119,7 +119,9 @@ def setup_filters(): r"The Session.begin.subtransactions flag is deprecated", ]: warnings.filterwarnings( - "ignore", message=msg, category=sa_exc.RemovedIn20Warning, + "ignore", + message=msg, + category=sa_exc.RemovedIn20Warning, ) try: diff --git a/lib/sqlalchemy/util/_collections.py b/lib/sqlalchemy/util/_collections.py index 7c109b358..b50d9885d 100644 --- a/lib/sqlalchemy/util/_collections.py +++ b/lib/sqlalchemy/util/_collections.py @@ -133,10 +133,7 @@ class FacadeDict(ImmutableContainer, dict): return FacadeDict, (dict(self),) def _insert_item(self, key, value): - """insert an item into the dictionary directly. - - - """ + """insert an item into the dictionary directly.""" dict.__setitem__(self, key, value) def __repr__(self): diff --git a/lib/sqlalchemy/util/compat.py b/lib/sqlalchemy/util/compat.py index e1d0e6444..285f6c021 100644 --- a/lib/sqlalchemy/util/compat.py +++ b/lib/sqlalchemy/util/compat.py @@ -309,8 +309,7 @@ else: if py3k: def _formatannotation(annotation, base_module=None): - """vendored from python 3.7 - """ + """vendored from python 3.7""" if getattr(annotation, "__module__", None) == "typing": return repr(annotation).replace("typing.", "") diff --git a/lib/sqlalchemy/util/deprecations.py b/lib/sqlalchemy/util/deprecations.py index eae4be768..83037bbff 100644 --- a/lib/sqlalchemy/util/deprecations.py +++ b/lib/sqlalchemy/util/deprecations.py @@ -131,7 +131,10 @@ def deprecated( warning = exc.RemovedIn20Warning version = "1.4" if add_deprecation_to_docstring: - header = ".. deprecated:: %s %s" % (version, (message or ""),) + header = ".. deprecated:: %s %s" % ( + version, + (message or ""), + ) else: header = None diff --git a/lib/sqlalchemy/util/langhelpers.py b/lib/sqlalchemy/util/langhelpers.py index e8abf3130..bbdd3381f 100644 --- a/lib/sqlalchemy/util/langhelpers.py +++ b/lib/sqlalchemy/util/langhelpers.py @@ -66,7 +66,8 @@ class safe_reraise(object): self._exc_info = None # remove potential circular references if not self.warn_only: compat.raise_( - exc_value, with_traceback=exc_tb, + exc_value, + with_traceback=exc_tb, ) else: if not compat.py3k and self._exc_info and self._exc_info[1]: @@ -731,10 +732,10 @@ def class_hierarchy(cls): def iterate_attributes(cls): """iterate all the keys and attributes associated - with a class, without using getattr(). + with a class, without using getattr(). - Does not use getattr() so that class-sensitive - descriptors (i.e. property.__get__()) are not called. + Does not use getattr() so that class-sensitive + descriptors (i.e. property.__get__()) are not called. """ keys = dir(cls) @@ -986,9 +987,7 @@ class HasMemoized(object): @classmethod def memoized_instancemethod(cls, fn): - """Decorate a method memoize its return value. - - """ + """Decorate a method memoize its return value.""" def oneshot(self, *args, **kw): result = fn(self, *args, **kw) @@ -1738,8 +1737,8 @@ def inject_param_text(doctext, inject_params): def repr_tuple_names(names): - """ Trims a list of strings from the middle and return a string of up to - four elements. Strings greater than 11 characters will be truncated""" + """Trims a list of strings from the middle and return a string of up to + four elements. Strings greater than 11 characters will be truncated""" if len(names) == 0: return None flag = len(names) <= 4 diff --git a/lib/sqlalchemy/util/queue.py b/lib/sqlalchemy/util/queue.py index 9447abede..3687dc8dc 100644 --- a/lib/sqlalchemy/util/queue.py +++ b/lib/sqlalchemy/util/queue.py @@ -220,7 +220,8 @@ class AsyncAdaptedQueue: return self._queue.put_nowait(item) except asyncio.queues.QueueFull as err: compat.raise_( - Full(), replace_context=err, + Full(), + replace_context=err, ) def put(self, item, block=True, timeout=None): @@ -236,7 +237,8 @@ class AsyncAdaptedQueue: return self.await_(self._queue.put(item)) except asyncio.queues.QueueFull as err: compat.raise_( - Full(), replace_context=err, + Full(), + replace_context=err, ) def get_nowait(self): @@ -244,7 +246,8 @@ class AsyncAdaptedQueue: return self._queue.get_nowait() except asyncio.queues.QueueEmpty as err: compat.raise_( - Empty(), replace_context=err, + Empty(), + replace_context=err, ) def get(self, block=True, timeout=None): @@ -259,5 +262,6 @@ class AsyncAdaptedQueue: return self.await_(self._queue.get()) except asyncio.queues.QueueEmpty as err: compat.raise_( - Empty(), replace_context=err, + Empty(), + replace_context=err, ) |
