]> git.ipfire.org Git - thirdparty/sqlalchemy/alembic.git/commitdiff
tooling: write_pyi.py: filter usage of raw-strings (rstrings)
authorJames Addison <james@reciperadar.com>
Mon, 10 Apr 2023 19:40:38 +0000 (15:40 -0400)
committerFederico Caselli <cfederico87@gmail.com>
Wed, 12 Apr 2023 20:36:39 +0000 (22:36 +0200)
### 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

alembic/context.pyi
alembic/op.pyi
alembic/operations/ops.py
setup.cfg
tools/write_pyi.py

index a262638b23c5a765c432a68cd33f9649756269b4..a9f48b226f30ea5b25b23a3098752ffebe5e5dab 100644 (file)
@@ -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
index 2f92dc3401493fcd4324869f0c89581d93175ad3..bb091c42a5e242b3c79a7b0b2c0e2f637e0fc73a 100644 (file)
@@ -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.
index a40704fdc2a8998faffbf01dc046b51232cae068..789fb58a68d93fc63ca556b30bc30c77d5952fba 100644 (file)
@@ -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
index 39c1540870e16a66b0e00c615d0e37d574e7f2f7..a7666ce5a29004b4704b4abfc8fc86b8b0ef9e93 100644 (file)
--- a/setup.cfg
+++ b/setup.cfg
@@ -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]
index fcf9d36307d112e6e4f8f4378a47319ee6e54792..4fbf36617ae2cfb54b401477d9ab5d736aac3409 100644 (file)
@@ -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"""