legacy.py 8.3 KB

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