diff options
author | James Addison <james@reciperadar.com> | 2023-04-10 15:40:38 -0400 |
---|---|---|
committer | Federico Caselli <cfederico87@gmail.com> | 2023-04-12 22:36:39 +0200 |
commit | d3f869bb3159d18669fb6f00cbe514307118eea7 (patch) | |
tree | 32b83d276b3eaf779dcea37aa1c59e0b0da5e596 | |
parent | 33a9947686a7c8bb3becd6169ec7abe84cf2c7e6 (diff) | |
download | alembic-d3f869bb3159d18669fb6f00cbe514307118eea7.tar.gz |
tooling: write_pyi.py: filter usage of raw-strings (rstrings)
### Description
While reading the diff between [`rel_1_10_2...rel_1_10_3`](https://github.com/sqlalchemy/alembic/compare/rel_1_10_2...rel_1_10_3), the introduction of r-strings drew my attention, and that resulted in some [discussion on the relevant commit](https://github.com/sqlalchemy/alembic/commit/bc0c305b7c2cc0401e250fcd6a725aacecdd6e33).
This changeset filters the production of r-strings during stub-generation to cases where docstrings contain escape (backslash, `\`) characters.
I'll admit that I didn't realize until today that these stubs are primarily for typechecking. Since that's the case, I have doubts about whether the change is worthwhile (consistency and simplicity -- using r-strings for all docstrings in the stubs -- even if it's redundant, seems fine to me).
### Checklist
This pull request is:
- [x] A documentation / typographical error fix
- [x] A short code fix
- Relates to discussion at https://github.com/sqlalchemy/alembic/commit/bc0c305b7c2cc0401e250fcd6a725aacecdd6e33
Closes: #1218
Pull-request: https://github.com/sqlalchemy/alembic/pull/1218
Pull-request-sha: 352ab8829525435f78838687e12156a3fa3a3d86
Closes: #1219
Pull-request: https://github.com/sqlalchemy/alembic/pull/1219
Change-Id: I2808a592681dabc093d538f589e673fcc5e05822
-rw-r--r-- | alembic/context.pyi | 30 | ||||
-rw-r--r-- | alembic/op.pyi | 69 | ||||
-rw-r--r-- | alembic/operations/ops.py | 18 | ||||
-rw-r--r-- | setup.cfg | 2 | ||||
-rw-r--r-- | tools/write_pyi.py | 3 |
5 files changed, 63 insertions, 59 deletions
diff --git a/alembic/context.pyi b/alembic/context.pyi index a262638..a9f48b2 100644 --- a/alembic/context.pyi +++ b/alembic/context.pyi @@ -29,7 +29,7 @@ if TYPE_CHECKING: ### end imports ### def begin_transaction() -> Union[_ProxyTransaction, ContextManager[None]]: - r"""Return a context manager that will + """Return a context manager that will enclose an operation within a "transaction", as defined by the environment's offline and transactional DDL settings. @@ -107,7 +107,7 @@ def configure( on_version_apply: Optional[Callable[..., None]] = None, **kw: Any, ) -> None: - r"""Configure a :class:`.MigrationContext` within this + """Configure a :class:`.MigrationContext` within this :class:`.EnvironmentContext` which will provide database connectivity and other configuration to a series of migration scripts. @@ -543,7 +543,7 @@ def configure( def execute( sql: Union[ClauseElement, str], execution_options: Optional[dict] = None ) -> None: - r"""Execute the given SQL using the current change context. + """Execute the given SQL using the current change context. The behavior of :meth:`.execute` is the same as that of :meth:`.Operations.execute`. Please see that @@ -556,7 +556,7 @@ def execute( """ def get_bind() -> Connection: - r"""Return the current 'bind'. + """Return the current 'bind'. In "online" mode, this is the :class:`sqlalchemy.engine.Connection` currently being used @@ -568,7 +568,7 @@ def get_bind() -> Connection: """ def get_context() -> MigrationContext: - r"""Return the current :class:`.MigrationContext` object. + """Return the current :class:`.MigrationContext` object. If :meth:`.EnvironmentContext.configure` has not been called yet, raises an exception. @@ -576,7 +576,7 @@ def get_context() -> MigrationContext: """ def get_head_revision() -> Union[str, Tuple[str, ...], None]: - r"""Return the hex identifier of the 'head' script revision. + """Return the hex identifier of the 'head' script revision. If the script directory has multiple heads, this method raises a :class:`.CommandError`; @@ -590,7 +590,7 @@ def get_head_revision() -> Union[str, Tuple[str, ...], None]: """ def get_head_revisions() -> Union[str, Tuple[str, ...], None]: - r"""Return the hex identifier of the 'heads' script revision(s). + """Return the hex identifier of the 'heads' script revision(s). This returns a tuple containing the version number of all heads in the script directory. @@ -601,7 +601,7 @@ def get_head_revisions() -> Union[str, Tuple[str, ...], None]: """ def get_revision_argument() -> Union[str, Tuple[str, ...], None]: - r"""Get the 'destination' revision argument. + """Get the 'destination' revision argument. This is typically the argument passed to the ``upgrade`` or ``downgrade`` command. @@ -616,7 +616,7 @@ def get_revision_argument() -> Union[str, Tuple[str, ...], None]: """ def get_starting_revision_argument() -> Union[str, Tuple[str, ...], None]: - r"""Return the 'starting revision' argument, + """Return the 'starting revision' argument, if the revision was passed using ``start:end``. This is only meaningful in "offline" mode. @@ -629,7 +629,7 @@ def get_starting_revision_argument() -> Union[str, Tuple[str, ...], None]: """ def get_tag_argument() -> Optional[str]: - r"""Return the value passed for the ``--tag`` argument, if any. + """Return the value passed for the ``--tag`` argument, if any. The ``--tag`` argument is not used directly by Alembic, but is available for custom ``env.py`` configurations that @@ -655,7 +655,7 @@ def get_x_argument(as_dictionary: Literal[True]) -> Dict[str, str]: ... def get_x_argument( as_dictionary: bool = ..., ) -> Union[List[str], Dict[str, str]]: - r"""Return the value(s) passed for the ``-x`` argument, if any. + """Return the value(s) passed for the ``-x`` argument, if any. The ``-x`` argument is an open ended flag that allows any user-defined value or values to be passed on the command line, then available @@ -695,7 +695,7 @@ def get_x_argument( """ def is_offline_mode() -> bool: - r"""Return True if the current migrations environment + """Return True if the current migrations environment is running in "offline mode". This is ``True`` or ``False`` depending @@ -707,7 +707,7 @@ def is_offline_mode() -> bool: """ def is_transactional_ddl(): - r"""Return True if the context is configured to expect a + """Return True if the context is configured to expect a transactional DDL capable backend. This defaults to the type of database in use, and @@ -720,7 +720,7 @@ def is_transactional_ddl(): """ def run_migrations(**kw: Any) -> None: - r"""Run migrations as determined by the current command line + """Run migrations as determined by the current command line configuration as well as versioning information present (or not) in the current database connection (if one is present). @@ -743,7 +743,7 @@ def run_migrations(**kw: Any) -> None: script: ScriptDirectory def static_output(text: str) -> None: - r"""Emit text directly to the "offline" SQL stream. + """Emit text directly to the "offline" SQL stream. Typically this is for emitting comments that start with --. The statement is not treated diff --git a/alembic/op.pyi b/alembic/op.pyi index 2f92dc3..bb091c4 100644 --- a/alembic/op.pyi +++ b/alembic/op.pyi @@ -1,5 +1,7 @@ # ### this file stubs are generated by tools/write_pyi.py - do not edit ### # ### imports are manually managed +from __future__ import annotations + from contextlib import contextmanager from typing import Any from typing import Callable @@ -19,7 +21,6 @@ from sqlalchemy.sql.expression import TableClause from sqlalchemy.sql.expression import Update if TYPE_CHECKING: - from sqlalchemy.engine import Connection from sqlalchemy.sql.elements import BinaryExpression from sqlalchemy.sql.elements import conv @@ -42,7 +43,7 @@ if TYPE_CHECKING: def add_column( table_name: str, column: Column, schema: Optional[str] = None ) -> Optional[Table]: - r"""Issue an "add column" instruction using the current + """Issue an "add column" instruction using the current migration context. e.g.:: @@ -106,7 +107,7 @@ def alter_column( existing_nullable: Optional[bool] = None, existing_comment: Optional[str] = None, schema: Optional[str] = None, - **kw: Any + **kw: Any, ) -> Optional[Table]: r"""Issue an "alter column" instruction using the current migration context. @@ -210,7 +211,7 @@ def batch_alter_table( reflect_kwargs: Mapping[str, Any] = immutabledict({}), naming_convention: Optional[Dict[str, str]] = None, ) -> Iterator[BatchOperations]: - r"""Invoke a series of per-table migrations in batch. + """Invoke a series of per-table migrations in batch. Batch mode allows a series of operations specific to a table to be syntactically grouped together, and allows for alternate @@ -352,7 +353,7 @@ def bulk_insert( rows: List[dict], multiinsert: bool = True, ) -> None: - r"""Issue a "bulk insert" operation using the current + """Issue a "bulk insert" operation using the current migration context. This provides a means of representing an INSERT of multiple rows @@ -432,9 +433,9 @@ def create_check_constraint( table_name: str, condition: Union[str, BinaryExpression], schema: Optional[str] = None, - **kw: Any + **kw: Any, ) -> Optional[Table]: - r"""Issue a "create check constraint" instruction using the + """Issue a "create check constraint" instruction using the current migration context. e.g.:: @@ -478,7 +479,7 @@ def create_check_constraint( def create_exclude_constraint( constraint_name: str, table_name: str, *elements: Any, **kw: Any ) -> Optional[Table]: - r"""Issue an alter to create an EXCLUDE constraint using the + """Issue an alter to create an EXCLUDE constraint using the current migration context. .. note:: This method is Postgresql specific, and additionally @@ -528,9 +529,9 @@ def create_foreign_key( match: Optional[str] = None, source_schema: Optional[str] = None, referent_schema: Optional[str] = None, - **dialect_kw: Any + **dialect_kw: Any, ) -> Optional[Table]: - r"""Issue a "create foreign key" instruction using the + """Issue a "create foreign key" instruction using the current migration context. e.g.:: @@ -581,7 +582,7 @@ def create_index( columns: Sequence[Union[str, TextClause, Function[Any]]], schema: Optional[str] = None, unique: bool = False, - **kw: Any + **kw: Any, ) -> Optional[Table]: r"""Issue a "create index" instruction using the current migration context. @@ -631,7 +632,7 @@ def create_primary_key( columns: List[str], schema: Optional[str] = None, ) -> Optional[Table]: - r"""Issue a "create primary key" instruction using the current + """Issue a "create primary key" instruction using the current migration context. e.g.:: @@ -754,7 +755,7 @@ def create_table_comment( existing_comment: None = None, schema: Optional[str] = None, ) -> Optional[Table]: - r"""Emit a COMMENT ON operation to set the comment for a table. + """Emit a COMMENT ON operation to set the comment for a table. .. versionadded:: 1.0.6 @@ -779,9 +780,9 @@ def create_unique_constraint( table_name: str, columns: Sequence[str], schema: Optional[str] = None, - **kw: Any + **kw: Any, ) -> Any: - r"""Issue a "create unique constraint" instruction using the + """Issue a "create unique constraint" instruction using the current migration context. e.g.:: @@ -822,7 +823,7 @@ def create_unique_constraint( def drop_column( table_name: str, column_name: str, schema: Optional[str] = None, **kw: Any ) -> Optional[Table]: - r"""Issue a "drop column" instruction using the current + """Issue a "drop column" instruction using the current migration context. e.g.:: @@ -882,7 +883,7 @@ def drop_index( index_name: str, table_name: Optional[str] = None, schema: Optional[str] = None, - **kw: Any + **kw: Any, ) -> Optional[Table]: r"""Issue a "drop index" instruction using the current migration context. @@ -932,7 +933,7 @@ def drop_table_comment( existing_comment: Optional[str] = None, schema: Optional[str] = None, ) -> Optional[Table]: - r"""Issue a "drop table comment" operation to + """Issue a "drop table comment" operation to remove an existing comment set on a table. .. versionadded:: 1.0.6 @@ -965,14 +966,12 @@ def execute( from sqlalchemy import String from alembic import op - account = table('account', - column('name', String) - ) + account = table("account", column("name", String)) op.execute( - account.update().\\ - where(account.c.name==op.inline_literal('account 1')).\\ - values({'name':op.inline_literal('account 2')}) - ) + account.update() + .where(account.c.name == op.inline_literal("account 1")) + .values({"name": op.inline_literal("account 2")}) + ) Above, we made use of the SQLAlchemy :func:`sqlalchemy.sql.expression.table` and @@ -996,11 +995,13 @@ def execute( also be used normally, use the "bind" available from the context:: from alembic import op + connection = op.get_bind() connection.execute( - account.update().where(account.c.name=='account 1'). - values({"name": "account 2"}) + account.update() + .where(account.c.name == "account 1") + .values({"name": "account 2"}) ) Additionally, when passing the statement as a plain string, it is first @@ -1035,7 +1036,7 @@ def execute( """ def f(name: str) -> conv: - r"""Indicate a string name that has already had a naming convention + """Indicate a string name that has already had a naming convention applied to it. This feature combines with the SQLAlchemy ``naming_convention`` feature @@ -1072,7 +1073,7 @@ def f(name: str) -> conv: """ def get_bind() -> Connection: - r"""Return the current 'bind'. + """Return the current 'bind'. Under normal circumstances, this is the :class:`~sqlalchemy.engine.Connection` currently being used @@ -1083,13 +1084,13 @@ def get_bind() -> Connection: """ def get_context() -> MigrationContext: - r"""Return the :class:`.MigrationContext` object that's + """Return the :class:`.MigrationContext` object that's currently in use. """ def implementation_for(op_cls: Any) -> Callable[..., Any]: - r"""Register an implementation for a given :class:`.MigrateOperation`. + """Register an implementation for a given :class:`.MigrateOperation`. This is part of the operation extensibility API. @@ -1145,7 +1146,7 @@ def inline_literal( """ def invoke(operation: MigrateOperation) -> Any: - r"""Given a :class:`.MigrateOperation`, invoke it in terms of + """Given a :class:`.MigrateOperation`, invoke it in terms of this :class:`.Operations` instance. """ @@ -1153,7 +1154,7 @@ def invoke(operation: MigrateOperation) -> Any: def register_operation( name: str, sourcename: Optional[str] = None ) -> Callable[..., Any]: - r"""Register a new operation for this class. + """Register a new operation for this class. This method is normally used to add new operations to the :class:`.Operations` class, and possibly the @@ -1172,7 +1173,7 @@ def register_operation( def rename_table( old_table_name: str, new_table_name: str, schema: Optional[str] = None ) -> Optional[Table]: - r"""Emit an ALTER TABLE to rename a table. + """Emit an ALTER TABLE to rename a table. :param old_table_name: old name. :param new_table_name: new name. diff --git a/alembic/operations/ops.py b/alembic/operations/ops.py index a40704f..789fb58 100644 --- a/alembic/operations/ops.py +++ b/alembic/operations/ops.py @@ -2339,14 +2339,12 @@ class ExecuteSQLOp(MigrateOperation): from sqlalchemy import String from alembic import op - account = table('account', - column('name', String) - ) + account = table("account", column("name", String)) op.execute( - account.update().\\ - where(account.c.name==op.inline_literal('account 1')).\\ - values({'name':op.inline_literal('account 2')}) - ) + account.update() + .where(account.c.name == op.inline_literal("account 1")) + .values({"name": op.inline_literal("account 2")}) + ) Above, we made use of the SQLAlchemy :func:`sqlalchemy.sql.expression.table` and @@ -2370,11 +2368,13 @@ class ExecuteSQLOp(MigrateOperation): also be used normally, use the "bind" available from the context:: from alembic import op + connection = op.get_bind() connection.execute( - account.update().where(account.c.name=='account 1'). - values({"name": "account 2"}) + account.update() + .where(account.c.name == "account 1") + .values({"name": "account 2"}) ) Additionally, when passing the statement as a plain string, it is first @@ -89,10 +89,12 @@ ignore = RST304,RST303,RST299,RST399, W503,W504 exclude = .venv,.git,.tox,dist,doc,*egg,build +filename = *.py,*.pyi import-order-style = google application-import-names = alembic,tests per-file-ignores = **/__init__.py:F401 + **/*.pyi:E302,E704,E266 max-line-length = 79 [sqla_testing] diff --git a/tools/write_pyi.py b/tools/write_pyi.py index fcf9d36..4fbf366 100644 --- a/tools/write_pyi.py +++ b/tools/write_pyi.py @@ -218,7 +218,8 @@ def _generate_stub_for_meth( fn_doc = base_method.__doc__ if base_method else fn.__doc__ has_docs = gen_docs and fn_doc is not None - docs = 'r"""' + f"{fn_doc}" + '"""' if has_docs else "" + string_prefix = "r" if chr(92) in fn_doc else "" + docs = f'{string_prefix}"""' + f"{fn_doc}" + '"""' if has_docs else "" func_text = textwrap.dedent( f""" |