legacy.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. # event/legacy.py
  2. # Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """Routines to handle adaption of legacy call signatures,
  8. generation of deprecation notes and docstrings.
  9. """
  10. from __future__ import annotations
  11. import typing
  12. from typing import Any
  13. from typing import Callable
  14. from typing import List
  15. from typing import Optional
  16. from typing import Tuple
  17. from typing import Type
  18. from .registry import _ET
  19. from .registry import _ListenerFnType
  20. from .. import util
  21. from ..util.compat import FullArgSpec
  22. if typing.TYPE_CHECKING:
  23. from .attr import _ClsLevelDispatch
  24. from .base import _HasEventsDispatch
  25. _LegacySignatureType = Tuple[str, List[str], Optional[Callable[..., Any]]]
  26. def _legacy_signature(
  27. since: str,
  28. argnames: List[str],
  29. converter: Optional[Callable[..., Any]] = None,
  30. ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
  31. """legacy sig decorator
  32. :param since: string version for deprecation warning
  33. :param argnames: list of strings, which is *all* arguments that the legacy
  34. version accepted, including arguments that are still there
  35. :param converter: lambda that will accept tuple of this full arg signature
  36. and return tuple of new arg signature.
  37. """
  38. def leg(fn: Callable[..., Any]) -> Callable[..., Any]:
  39. if not hasattr(fn, "_legacy_signatures"):
  40. fn._legacy_signatures = [] # type: ignore[attr-defined]
  41. fn._legacy_signatures.append((since, argnames, converter)) # type: ignore[attr-defined] # noqa: E501
  42. return fn
  43. return leg
  44. def _wrap_fn_for_legacy(
  45. dispatch_collection: _ClsLevelDispatch[_ET],
  46. fn: _ListenerFnType,
  47. argspec: FullArgSpec,
  48. ) -> _ListenerFnType:
  49. for since, argnames, conv in dispatch_collection.legacy_signatures:
  50. if argnames[-1] == "**kw":
  51. has_kw = True
  52. argnames = argnames[0:-1]
  53. else:
  54. has_kw = False
  55. if len(argnames) == len(argspec.args) and has_kw is bool(
  56. argspec.varkw
  57. ):
  58. formatted_def = "def %s(%s%s)" % (
  59. dispatch_collection.name,
  60. ", ".join(dispatch_collection.arg_names),
  61. ", **kw" if has_kw else "",
  62. )
  63. warning_txt = (
  64. 'The argument signature for the "%s.%s" event listener '
  65. "has changed as of version %s, and conversion for "
  66. "the old argument signature will be removed in a "
  67. 'future release. The new signature is "%s"'
  68. % (
  69. dispatch_collection.clsname,
  70. dispatch_collection.name,
  71. since,
  72. formatted_def,
  73. )
  74. )
  75. if conv is not None:
  76. assert not has_kw
  77. def wrap_leg(*args: Any, **kw: Any) -> Any:
  78. util.warn_deprecated(warning_txt, version=since)
  79. assert conv is not None
  80. return fn(*conv(*args))
  81. else:
  82. def wrap_leg(*args: Any, **kw: Any) -> Any:
  83. util.warn_deprecated(warning_txt, version=since)
  84. argdict = dict(zip(dispatch_collection.arg_names, args))
  85. args_from_dict = [argdict[name] for name in argnames]
  86. if has_kw:
  87. return fn(*args_from_dict, **kw)
  88. else:
  89. return fn(*args_from_dict)
  90. return wrap_leg
  91. else:
  92. return fn
  93. def _indent(text: str, indent: str) -> str:
  94. return "\n".join(indent + line for line in text.split("\n"))
  95. def _standard_listen_example(
  96. dispatch_collection: _ClsLevelDispatch[_ET],
  97. sample_target: Any,
  98. fn: _ListenerFnType,
  99. ) -> str:
  100. example_kw_arg = _indent(
  101. "\n".join(
  102. "%(arg)s = kw['%(arg)s']" % {"arg": arg}
  103. for arg in dispatch_collection.arg_names[0:2]
  104. ),
  105. " ",
  106. )
  107. if dispatch_collection.legacy_signatures:
  108. current_since = max(
  109. since
  110. for since, args, conv in dispatch_collection.legacy_signatures
  111. )
  112. else:
  113. current_since = None
  114. text = (
  115. "from sqlalchemy import event\n\n\n"
  116. "@event.listens_for(%(sample_target)s, '%(event_name)s')\n"
  117. "def receive_%(event_name)s("
  118. "%(named_event_arguments)s%(has_kw_arguments)s):\n"
  119. " \"listen for the '%(event_name)s' event\"\n"
  120. "\n # ... (event handling logic) ...\n"
  121. )
  122. text %= {
  123. "current_since": (
  124. " (arguments as of %s)" % current_since if current_since else ""
  125. ),
  126. "event_name": fn.__name__,
  127. "has_kw_arguments": ", **kw" if dispatch_collection.has_kw else "",
  128. "named_event_arguments": ", ".join(dispatch_collection.arg_names),
  129. "example_kw_arg": example_kw_arg,
  130. "sample_target": sample_target,
  131. }
  132. return text
  133. def _legacy_listen_examples(
  134. dispatch_collection: _ClsLevelDispatch[_ET],
  135. sample_target: str,
  136. fn: _ListenerFnType,
  137. ) -> str:
  138. text = ""
  139. for since, args, conv in dispatch_collection.legacy_signatures:
  140. text += (
  141. "\n# DEPRECATED calling style (pre-%(since)s, "
  142. "will be removed in a future release)\n"
  143. "@event.listens_for(%(sample_target)s, '%(event_name)s')\n"
  144. "def receive_%(event_name)s("
  145. "%(named_event_arguments)s%(has_kw_arguments)s):\n"
  146. " \"listen for the '%(event_name)s' event\"\n"
  147. "\n # ... (event handling logic) ...\n"
  148. % {
  149. "since": since,
  150. "event_name": fn.__name__,
  151. "has_kw_arguments": (
  152. " **kw" if dispatch_collection.has_kw else ""
  153. ),
  154. "named_event_arguments": ", ".join(args),
  155. "sample_target": sample_target,
  156. }
  157. )
  158. return text
  159. def _version_signature_changes(
  160. parent_dispatch_cls: Type[_HasEventsDispatch[_ET]],
  161. dispatch_collection: _ClsLevelDispatch[_ET],
  162. ) -> str:
  163. since, args, conv = dispatch_collection.legacy_signatures[0]
  164. return (
  165. "\n.. versionchanged:: %(since)s\n"
  166. " The :meth:`.%(clsname)s.%(event_name)s` event now accepts the \n"
  167. " arguments %(named_event_arguments)s%(has_kw_arguments)s.\n"
  168. " Support for listener functions which accept the previous \n"
  169. ' argument signature(s) listed above as "deprecated" will be \n'
  170. " removed in a future release."
  171. % {
  172. "since": since,
  173. "clsname": parent_dispatch_cls.__name__,
  174. "event_name": dispatch_collection.name,
  175. "named_event_arguments": ", ".join(
  176. ":paramref:`.%(clsname)s.%(event_name)s.%(param_name)s`"
  177. % {
  178. "clsname": parent_dispatch_cls.__name__,
  179. "event_name": dispatch_collection.name,
  180. "param_name": param_name,
  181. }
  182. for param_name in dispatch_collection.arg_names
  183. ),
  184. "has_kw_arguments": ", **kw" if dispatch_collection.has_kw else "",
  185. }
  186. )
  187. def _augment_fn_docs(
  188. dispatch_collection: _ClsLevelDispatch[_ET],
  189. parent_dispatch_cls: Type[_HasEventsDispatch[_ET]],
  190. fn: _ListenerFnType,
  191. ) -> str:
  192. header = (
  193. ".. container:: event_signatures\n\n"
  194. " Example argument forms::\n"
  195. "\n"
  196. )
  197. sample_target = getattr(parent_dispatch_cls, "_target_class_doc", "obj")
  198. text = header + _indent(
  199. _standard_listen_example(dispatch_collection, sample_target, fn),
  200. " " * 8,
  201. )
  202. if dispatch_collection.legacy_signatures:
  203. text += _indent(
  204. _legacy_listen_examples(dispatch_collection, sample_target, fn),
  205. " " * 8,
  206. )
  207. text += _version_signature_changes(
  208. parent_dispatch_cls, dispatch_collection
  209. )
  210. return util.inject_docstring_text(fn.__doc__, text, 1)