_hooks.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. """
  2. Internal hook annotation, representation and calling machinery.
  3. """
  4. from __future__ import annotations
  5. import inspect
  6. import sys
  7. from types import ModuleType
  8. from typing import AbstractSet
  9. from typing import Any
  10. from typing import Callable
  11. from typing import Final
  12. from typing import final
  13. from typing import Generator
  14. from typing import List
  15. from typing import Mapping
  16. from typing import Optional
  17. from typing import overload
  18. from typing import Sequence
  19. from typing import Tuple
  20. from typing import TYPE_CHECKING
  21. from typing import TypedDict
  22. from typing import TypeVar
  23. from typing import Union
  24. import warnings
  25. from ._result import Result
  26. _T = TypeVar("_T")
  27. _F = TypeVar("_F", bound=Callable[..., object])
  28. _Namespace = Union[ModuleType, type]
  29. _Plugin = object
  30. _HookExec = Callable[
  31. [str, Sequence["HookImpl"], Mapping[str, object], bool],
  32. Union[object, List[object]],
  33. ]
  34. _HookImplFunction = Callable[..., Union[_T, Generator[None, Result[_T], None]]]
  35. class HookspecOpts(TypedDict):
  36. """Options for a hook specification."""
  37. #: Whether the hook is :ref:`first result only <firstresult>`.
  38. firstresult: bool
  39. #: Whether the hook is :ref:`historic <historic>`.
  40. historic: bool
  41. #: Whether the hook :ref:`warns when implemented <warn_on_impl>`.
  42. warn_on_impl: Warning | None
  43. #: Whether the hook warns when :ref:`certain arguments are requested
  44. #: <warn_on_impl>`.
  45. #:
  46. #: .. versionadded:: 1.5
  47. warn_on_impl_args: Mapping[str, Warning] | None
  48. class HookimplOpts(TypedDict):
  49. """Options for a hook implementation."""
  50. #: Whether the hook implementation is a :ref:`wrapper <hookwrapper>`.
  51. wrapper: bool
  52. #: Whether the hook implementation is an :ref:`old-style wrapper
  53. #: <old_style_hookwrappers>`.
  54. hookwrapper: bool
  55. #: Whether validation against a hook specification is :ref:`optional
  56. #: <optionalhook>`.
  57. optionalhook: bool
  58. #: Whether to try to order this hook implementation :ref:`first
  59. #: <callorder>`.
  60. tryfirst: bool
  61. #: Whether to try to order this hook implementation :ref:`last
  62. #: <callorder>`.
  63. trylast: bool
  64. #: The name of the hook specification to match, see :ref:`specname`.
  65. specname: str | None
  66. @final
  67. class HookspecMarker:
  68. """Decorator for marking functions as hook specifications.
  69. Instantiate it with a project_name to get a decorator.
  70. Calling :meth:`PluginManager.add_hookspecs` later will discover all marked
  71. functions if the :class:`PluginManager` uses the same project name.
  72. """
  73. __slots__ = ("project_name",)
  74. def __init__(self, project_name: str) -> None:
  75. self.project_name: Final = project_name
  76. @overload
  77. def __call__(
  78. self,
  79. function: _F,
  80. firstresult: bool = False,
  81. historic: bool = False,
  82. warn_on_impl: Warning | None = None,
  83. warn_on_impl_args: Mapping[str, Warning] | None = None,
  84. ) -> _F: ...
  85. @overload # noqa: F811
  86. def __call__( # noqa: F811
  87. self,
  88. function: None = ...,
  89. firstresult: bool = ...,
  90. historic: bool = ...,
  91. warn_on_impl: Warning | None = ...,
  92. warn_on_impl_args: Mapping[str, Warning] | None = ...,
  93. ) -> Callable[[_F], _F]: ...
  94. def __call__( # noqa: F811
  95. self,
  96. function: _F | None = None,
  97. firstresult: bool = False,
  98. historic: bool = False,
  99. warn_on_impl: Warning | None = None,
  100. warn_on_impl_args: Mapping[str, Warning] | None = None,
  101. ) -> _F | Callable[[_F], _F]:
  102. """If passed a function, directly sets attributes on the function
  103. which will make it discoverable to :meth:`PluginManager.add_hookspecs`.
  104. If passed no function, returns a decorator which can be applied to a
  105. function later using the attributes supplied.
  106. :param firstresult:
  107. If ``True``, the 1:N hook call (N being the number of registered
  108. hook implementation functions) will stop at I<=N when the I'th
  109. function returns a non-``None`` result. See :ref:`firstresult`.
  110. :param historic:
  111. If ``True``, every call to the hook will be memorized and replayed
  112. on plugins registered after the call was made. See :ref:`historic`.
  113. :param warn_on_impl:
  114. If given, every implementation of this hook will trigger the given
  115. warning. See :ref:`warn_on_impl`.
  116. :param warn_on_impl_args:
  117. If given, every implementation of this hook which requests one of
  118. the arguments in the dict will trigger the corresponding warning.
  119. See :ref:`warn_on_impl`.
  120. .. versionadded:: 1.5
  121. """
  122. def setattr_hookspec_opts(func: _F) -> _F:
  123. if historic and firstresult:
  124. raise ValueError("cannot have a historic firstresult hook")
  125. opts: HookspecOpts = {
  126. "firstresult": firstresult,
  127. "historic": historic,
  128. "warn_on_impl": warn_on_impl,
  129. "warn_on_impl_args": warn_on_impl_args,
  130. }
  131. setattr(func, self.project_name + "_spec", opts)
  132. return func
  133. if function is not None:
  134. return setattr_hookspec_opts(function)
  135. else:
  136. return setattr_hookspec_opts
  137. @final
  138. class HookimplMarker:
  139. """Decorator for marking functions as hook implementations.
  140. Instantiate it with a ``project_name`` to get a decorator.
  141. Calling :meth:`PluginManager.register` later will discover all marked
  142. functions if the :class:`PluginManager` uses the same project name.
  143. """
  144. __slots__ = ("project_name",)
  145. def __init__(self, project_name: str) -> None:
  146. self.project_name: Final = project_name
  147. @overload
  148. def __call__(
  149. self,
  150. function: _F,
  151. hookwrapper: bool = ...,
  152. optionalhook: bool = ...,
  153. tryfirst: bool = ...,
  154. trylast: bool = ...,
  155. specname: str | None = ...,
  156. wrapper: bool = ...,
  157. ) -> _F: ...
  158. @overload # noqa: F811
  159. def __call__( # noqa: F811
  160. self,
  161. function: None = ...,
  162. hookwrapper: bool = ...,
  163. optionalhook: bool = ...,
  164. tryfirst: bool = ...,
  165. trylast: bool = ...,
  166. specname: str | None = ...,
  167. wrapper: bool = ...,
  168. ) -> Callable[[_F], _F]: ...
  169. def __call__( # noqa: F811
  170. self,
  171. function: _F | None = None,
  172. hookwrapper: bool = False,
  173. optionalhook: bool = False,
  174. tryfirst: bool = False,
  175. trylast: bool = False,
  176. specname: str | None = None,
  177. wrapper: bool = False,
  178. ) -> _F | Callable[[_F], _F]:
  179. """If passed a function, directly sets attributes on the function
  180. which will make it discoverable to :meth:`PluginManager.register`.
  181. If passed no function, returns a decorator which can be applied to a
  182. function later using the attributes supplied.
  183. :param optionalhook:
  184. If ``True``, a missing matching hook specification will not result
  185. in an error (by default it is an error if no matching spec is
  186. found). See :ref:`optionalhook`.
  187. :param tryfirst:
  188. If ``True``, this hook implementation will run as early as possible
  189. in the chain of N hook implementations for a specification. See
  190. :ref:`callorder`.
  191. :param trylast:
  192. If ``True``, this hook implementation will run as late as possible
  193. in the chain of N hook implementations for a specification. See
  194. :ref:`callorder`.
  195. :param wrapper:
  196. If ``True`` ("new-style hook wrapper"), the hook implementation
  197. needs to execute exactly one ``yield``. The code before the
  198. ``yield`` is run early before any non-hook-wrapper function is run.
  199. The code after the ``yield`` is run after all non-hook-wrapper
  200. functions have run. The ``yield`` receives the result value of the
  201. inner calls, or raises the exception of inner calls (including
  202. earlier hook wrapper calls). The return value of the function
  203. becomes the return value of the hook, and a raised exception becomes
  204. the exception of the hook. See :ref:`hookwrapper`.
  205. :param hookwrapper:
  206. If ``True`` ("old-style hook wrapper"), the hook implementation
  207. needs to execute exactly one ``yield``. The code before the
  208. ``yield`` is run early before any non-hook-wrapper function is run.
  209. The code after the ``yield`` is run after all non-hook-wrapper
  210. function have run The ``yield`` receives a :class:`Result` object
  211. representing the exception or result outcome of the inner calls
  212. (including earlier hook wrapper calls). This option is mutually
  213. exclusive with ``wrapper``. See :ref:`old_style_hookwrapper`.
  214. :param specname:
  215. If provided, the given name will be used instead of the function
  216. name when matching this hook implementation to a hook specification
  217. during registration. See :ref:`specname`.
  218. .. versionadded:: 1.2.0
  219. The ``wrapper`` parameter.
  220. """
  221. def setattr_hookimpl_opts(func: _F) -> _F:
  222. opts: HookimplOpts = {
  223. "wrapper": wrapper,
  224. "hookwrapper": hookwrapper,
  225. "optionalhook": optionalhook,
  226. "tryfirst": tryfirst,
  227. "trylast": trylast,
  228. "specname": specname,
  229. }
  230. setattr(func, self.project_name + "_impl", opts)
  231. return func
  232. if function is None:
  233. return setattr_hookimpl_opts
  234. else:
  235. return setattr_hookimpl_opts(function)
  236. def normalize_hookimpl_opts(opts: HookimplOpts) -> None:
  237. opts.setdefault("tryfirst", False)
  238. opts.setdefault("trylast", False)
  239. opts.setdefault("wrapper", False)
  240. opts.setdefault("hookwrapper", False)
  241. opts.setdefault("optionalhook", False)
  242. opts.setdefault("specname", None)
  243. _PYPY = hasattr(sys, "pypy_version_info")
  244. def varnames(func: object) -> tuple[tuple[str, ...], tuple[str, ...]]:
  245. """Return tuple of positional and keywrord argument names for a function,
  246. method, class or callable.
  247. In case of a class, its ``__init__`` method is considered.
  248. For methods the ``self`` parameter is not included.
  249. """
  250. if inspect.isclass(func):
  251. try:
  252. func = func.__init__
  253. except AttributeError:
  254. return (), ()
  255. elif not inspect.isroutine(func): # callable object?
  256. try:
  257. func = getattr(func, "__call__", func)
  258. except Exception:
  259. return (), ()
  260. try:
  261. # func MUST be a function or method here or we won't parse any args.
  262. sig = inspect.signature(
  263. func.__func__ if inspect.ismethod(func) else func # type:ignore[arg-type]
  264. )
  265. except TypeError:
  266. return (), ()
  267. _valid_param_kinds = (
  268. inspect.Parameter.POSITIONAL_ONLY,
  269. inspect.Parameter.POSITIONAL_OR_KEYWORD,
  270. )
  271. _valid_params = {
  272. name: param
  273. for name, param in sig.parameters.items()
  274. if param.kind in _valid_param_kinds
  275. }
  276. args = tuple(_valid_params)
  277. defaults = (
  278. tuple(
  279. param.default
  280. for param in _valid_params.values()
  281. if param.default is not param.empty
  282. )
  283. or None
  284. )
  285. if defaults:
  286. index = -len(defaults)
  287. args, kwargs = args[:index], tuple(args[index:])
  288. else:
  289. kwargs = ()
  290. # strip any implicit instance arg
  291. # pypy3 uses "obj" instead of "self" for default dunder methods
  292. if not _PYPY:
  293. implicit_names: tuple[str, ...] = ("self",)
  294. else:
  295. implicit_names = ("self", "obj")
  296. if args:
  297. qualname: str = getattr(func, "__qualname__", "")
  298. if inspect.ismethod(func) or ("." in qualname and args[0] in implicit_names):
  299. args = args[1:]
  300. return args, kwargs
  301. @final
  302. class HookRelay:
  303. """Hook holder object for performing 1:N hook calls where N is the number
  304. of registered plugins."""
  305. __slots__ = ("__dict__",)
  306. def __init__(self) -> None:
  307. """:meta private:"""
  308. if TYPE_CHECKING:
  309. def __getattr__(self, name: str) -> HookCaller: ...
  310. # Historical name (pluggy<=1.2), kept for backward compatibility.
  311. _HookRelay = HookRelay
  312. _CallHistory = List[Tuple[Mapping[str, object], Optional[Callable[[Any], None]]]]
  313. class HookCaller:
  314. """A caller of all registered implementations of a hook specification."""
  315. __slots__ = (
  316. "name",
  317. "spec",
  318. "_hookexec",
  319. "_hookimpls",
  320. "_call_history",
  321. )
  322. def __init__(
  323. self,
  324. name: str,
  325. hook_execute: _HookExec,
  326. specmodule_or_class: _Namespace | None = None,
  327. spec_opts: HookspecOpts | None = None,
  328. ) -> None:
  329. """:meta private:"""
  330. #: Name of the hook getting called.
  331. self.name: Final = name
  332. self._hookexec: Final = hook_execute
  333. # The hookimpls list. The caller iterates it *in reverse*. Format:
  334. # 1. trylast nonwrappers
  335. # 2. nonwrappers
  336. # 3. tryfirst nonwrappers
  337. # 4. trylast wrappers
  338. # 5. wrappers
  339. # 6. tryfirst wrappers
  340. self._hookimpls: Final[list[HookImpl]] = []
  341. self._call_history: _CallHistory | None = None
  342. # TODO: Document, or make private.
  343. self.spec: HookSpec | None = None
  344. if specmodule_or_class is not None:
  345. assert spec_opts is not None
  346. self.set_specification(specmodule_or_class, spec_opts)
  347. # TODO: Document, or make private.
  348. def has_spec(self) -> bool:
  349. return self.spec is not None
  350. # TODO: Document, or make private.
  351. def set_specification(
  352. self,
  353. specmodule_or_class: _Namespace,
  354. spec_opts: HookspecOpts,
  355. ) -> None:
  356. if self.spec is not None:
  357. raise ValueError(
  358. f"Hook {self.spec.name!r} is already registered "
  359. f"within namespace {self.spec.namespace}"
  360. )
  361. self.spec = HookSpec(specmodule_or_class, self.name, spec_opts)
  362. if spec_opts.get("historic"):
  363. self._call_history = []
  364. def is_historic(self) -> bool:
  365. """Whether this caller is :ref:`historic <historic>`."""
  366. return self._call_history is not None
  367. def _remove_plugin(self, plugin: _Plugin) -> None:
  368. for i, method in enumerate(self._hookimpls):
  369. if method.plugin == plugin:
  370. del self._hookimpls[i]
  371. return
  372. raise ValueError(f"plugin {plugin!r} not found")
  373. def get_hookimpls(self) -> list[HookImpl]:
  374. """Get all registered hook implementations for this hook."""
  375. return self._hookimpls.copy()
  376. def _add_hookimpl(self, hookimpl: HookImpl) -> None:
  377. """Add an implementation to the callback chain."""
  378. for i, method in enumerate(self._hookimpls):
  379. if method.hookwrapper or method.wrapper:
  380. splitpoint = i
  381. break
  382. else:
  383. splitpoint = len(self._hookimpls)
  384. if hookimpl.hookwrapper or hookimpl.wrapper:
  385. start, end = splitpoint, len(self._hookimpls)
  386. else:
  387. start, end = 0, splitpoint
  388. if hookimpl.trylast:
  389. self._hookimpls.insert(start, hookimpl)
  390. elif hookimpl.tryfirst:
  391. self._hookimpls.insert(end, hookimpl)
  392. else:
  393. # find last non-tryfirst method
  394. i = end - 1
  395. while i >= start and self._hookimpls[i].tryfirst:
  396. i -= 1
  397. self._hookimpls.insert(i + 1, hookimpl)
  398. def __repr__(self) -> str:
  399. return f"<HookCaller {self.name!r}>"
  400. def _verify_all_args_are_provided(self, kwargs: Mapping[str, object]) -> None:
  401. # This is written to avoid expensive operations when not needed.
  402. if self.spec:
  403. for argname in self.spec.argnames:
  404. if argname not in kwargs:
  405. notincall = ", ".join(
  406. repr(argname)
  407. for argname in self.spec.argnames
  408. # Avoid self.spec.argnames - kwargs.keys() - doesn't preserve order.
  409. if argname not in kwargs.keys()
  410. )
  411. warnings.warn(
  412. "Argument(s) {} which are declared in the hookspec "
  413. "cannot be found in this hook call".format(notincall),
  414. stacklevel=2,
  415. )
  416. break
  417. def __call__(self, **kwargs: object) -> Any:
  418. """Call the hook.
  419. Only accepts keyword arguments, which should match the hook
  420. specification.
  421. Returns the result(s) of calling all registered plugins, see
  422. :ref:`calling`.
  423. """
  424. assert (
  425. not self.is_historic()
  426. ), "Cannot directly call a historic hook - use call_historic instead."
  427. self._verify_all_args_are_provided(kwargs)
  428. firstresult = self.spec.opts.get("firstresult", False) if self.spec else False
  429. # Copy because plugins may register other plugins during iteration (#438).
  430. return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult)
  431. def call_historic(
  432. self,
  433. result_callback: Callable[[Any], None] | None = None,
  434. kwargs: Mapping[str, object] | None = None,
  435. ) -> None:
  436. """Call the hook with given ``kwargs`` for all registered plugins and
  437. for all plugins which will be registered afterwards, see
  438. :ref:`historic`.
  439. :param result_callback:
  440. If provided, will be called for each non-``None`` result obtained
  441. from a hook implementation.
  442. """
  443. assert self._call_history is not None
  444. kwargs = kwargs or {}
  445. self._verify_all_args_are_provided(kwargs)
  446. self._call_history.append((kwargs, result_callback))
  447. # Historizing hooks don't return results.
  448. # Remember firstresult isn't compatible with historic.
  449. # Copy because plugins may register other plugins during iteration (#438).
  450. res = self._hookexec(self.name, self._hookimpls.copy(), kwargs, False)
  451. if result_callback is None:
  452. return
  453. if isinstance(res, list):
  454. for x in res:
  455. result_callback(x)
  456. def call_extra(
  457. self, methods: Sequence[Callable[..., object]], kwargs: Mapping[str, object]
  458. ) -> Any:
  459. """Call the hook with some additional temporarily participating
  460. methods using the specified ``kwargs`` as call parameters, see
  461. :ref:`call_extra`."""
  462. assert (
  463. not self.is_historic()
  464. ), "Cannot directly call a historic hook - use call_historic instead."
  465. self._verify_all_args_are_provided(kwargs)
  466. opts: HookimplOpts = {
  467. "wrapper": False,
  468. "hookwrapper": False,
  469. "optionalhook": False,
  470. "trylast": False,
  471. "tryfirst": False,
  472. "specname": None,
  473. }
  474. hookimpls = self._hookimpls.copy()
  475. for method in methods:
  476. hookimpl = HookImpl(None, "<temp>", method, opts)
  477. # Find last non-tryfirst nonwrapper method.
  478. i = len(hookimpls) - 1
  479. while i >= 0 and (
  480. # Skip wrappers.
  481. (hookimpls[i].hookwrapper or hookimpls[i].wrapper)
  482. # Skip tryfirst nonwrappers.
  483. or hookimpls[i].tryfirst
  484. ):
  485. i -= 1
  486. hookimpls.insert(i + 1, hookimpl)
  487. firstresult = self.spec.opts.get("firstresult", False) if self.spec else False
  488. return self._hookexec(self.name, hookimpls, kwargs, firstresult)
  489. def _maybe_apply_history(self, method: HookImpl) -> None:
  490. """Apply call history to a new hookimpl if it is marked as historic."""
  491. if self.is_historic():
  492. assert self._call_history is not None
  493. for kwargs, result_callback in self._call_history:
  494. res = self._hookexec(self.name, [method], kwargs, False)
  495. if res and result_callback is not None:
  496. # XXX: remember firstresult isn't compat with historic
  497. assert isinstance(res, list)
  498. result_callback(res[0])
  499. # Historical name (pluggy<=1.2), kept for backward compatibility.
  500. _HookCaller = HookCaller
  501. class _SubsetHookCaller(HookCaller):
  502. """A proxy to another HookCaller which manages calls to all registered
  503. plugins except the ones from remove_plugins."""
  504. # This class is unusual: in inhertits from `HookCaller` so all of
  505. # the *code* runs in the class, but it delegates all underlying *data*
  506. # to the original HookCaller.
  507. # `subset_hook_caller` used to be implemented by creating a full-fledged
  508. # HookCaller, copying all hookimpls from the original. This had problems
  509. # with memory leaks (#346) and historic calls (#347), which make a proxy
  510. # approach better.
  511. # An alternative implementation is to use a `_getattr__`/`__getattribute__`
  512. # proxy, however that adds more overhead and is more tricky to implement.
  513. __slots__ = (
  514. "_orig",
  515. "_remove_plugins",
  516. )
  517. def __init__(self, orig: HookCaller, remove_plugins: AbstractSet[_Plugin]) -> None:
  518. self._orig = orig
  519. self._remove_plugins = remove_plugins
  520. self.name = orig.name # type: ignore[misc]
  521. self._hookexec = orig._hookexec # type: ignore[misc]
  522. @property # type: ignore[misc]
  523. def _hookimpls(self) -> list[HookImpl]:
  524. return [
  525. impl
  526. for impl in self._orig._hookimpls
  527. if impl.plugin not in self._remove_plugins
  528. ]
  529. @property
  530. def spec(self) -> HookSpec | None: # type: ignore[override]
  531. return self._orig.spec
  532. @property
  533. def _call_history(self) -> _CallHistory | None: # type: ignore[override]
  534. return self._orig._call_history
  535. def __repr__(self) -> str:
  536. return f"<_SubsetHookCaller {self.name!r}>"
  537. @final
  538. class HookImpl:
  539. """A hook implementation in a :class:`HookCaller`."""
  540. __slots__ = (
  541. "function",
  542. "argnames",
  543. "kwargnames",
  544. "plugin",
  545. "opts",
  546. "plugin_name",
  547. "wrapper",
  548. "hookwrapper",
  549. "optionalhook",
  550. "tryfirst",
  551. "trylast",
  552. )
  553. def __init__(
  554. self,
  555. plugin: _Plugin,
  556. plugin_name: str,
  557. function: _HookImplFunction[object],
  558. hook_impl_opts: HookimplOpts,
  559. ) -> None:
  560. """:meta private:"""
  561. #: The hook implementation function.
  562. self.function: Final = function
  563. argnames, kwargnames = varnames(self.function)
  564. #: The positional parameter names of ``function```.
  565. self.argnames: Final = argnames
  566. #: The keyword parameter names of ``function```.
  567. self.kwargnames: Final = kwargnames
  568. #: The plugin which defined this hook implementation.
  569. self.plugin: Final = plugin
  570. #: The :class:`HookimplOpts` used to configure this hook implementation.
  571. self.opts: Final = hook_impl_opts
  572. #: The name of the plugin which defined this hook implementation.
  573. self.plugin_name: Final = plugin_name
  574. #: Whether the hook implementation is a :ref:`wrapper <hookwrapper>`.
  575. self.wrapper: Final = hook_impl_opts["wrapper"]
  576. #: Whether the hook implementation is an :ref:`old-style wrapper
  577. #: <old_style_hookwrappers>`.
  578. self.hookwrapper: Final = hook_impl_opts["hookwrapper"]
  579. #: Whether validation against a hook specification is :ref:`optional
  580. #: <optionalhook>`.
  581. self.optionalhook: Final = hook_impl_opts["optionalhook"]
  582. #: Whether to try to order this hook implementation :ref:`first
  583. #: <callorder>`.
  584. self.tryfirst: Final = hook_impl_opts["tryfirst"]
  585. #: Whether to try to order this hook implementation :ref:`last
  586. #: <callorder>`.
  587. self.trylast: Final = hook_impl_opts["trylast"]
  588. def __repr__(self) -> str:
  589. return f"<HookImpl plugin_name={self.plugin_name!r}, plugin={self.plugin!r}>"
  590. @final
  591. class HookSpec:
  592. __slots__ = (
  593. "namespace",
  594. "function",
  595. "name",
  596. "argnames",
  597. "kwargnames",
  598. "opts",
  599. "warn_on_impl",
  600. "warn_on_impl_args",
  601. )
  602. def __init__(self, namespace: _Namespace, name: str, opts: HookspecOpts) -> None:
  603. self.namespace = namespace
  604. self.function: Callable[..., object] = getattr(namespace, name)
  605. self.name = name
  606. self.argnames, self.kwargnames = varnames(self.function)
  607. self.opts = opts
  608. self.warn_on_impl = opts.get("warn_on_impl")
  609. self.warn_on_impl_args = opts.get("warn_on_impl_args")