From 4496c4adf08e1cbb637075e38b521014490610fd Mon Sep 17 00:00:00 2001 From: Ronny Pfannschmidt Date: Fri, 24 Jul 2026 10:49:45 +0200 Subject: [PATCH 1/3] docs(design): commit refactoring design writeups into history Add the design/ writeup chain (decisions + per-step docs 01-07) that guides the stacked refactoring branches. Exclude design/ from blacken-docs since the docs use elided pseudo-code signatures. Co-Authored-By: Claude Fable 5 --- .pre-commit-config.yaml | 1 + design/01-module-reorganization.md | 99 ++++++++++++ design/02-configuration-objects.md | 149 +++++++++++++++++ design/03-markers-attach-config.md | 102 ++++++++++++ design/04-hookimpl-wrapper-types.md | 169 ++++++++++++++++++++ design/05-hookcaller-and-execution.md | 222 ++++++++++++++++++++++++++ design/06-project-spec.md | 104 ++++++++++++ design/07-async-submitter.md | 169 ++++++++++++++++++++ design/DECISIONS.md | 140 ++++++++++++++++ design/README.md | 115 +++++++++++++ 10 files changed, 1270 insertions(+) create mode 100644 design/01-module-reorganization.md create mode 100644 design/02-configuration-objects.md create mode 100644 design/03-markers-attach-config.md create mode 100644 design/04-hookimpl-wrapper-types.md create mode 100644 design/05-hookcaller-and-execution.md create mode 100644 design/06-project-spec.md create mode 100644 design/07-async-submitter.md create mode 100644 design/DECISIONS.md create mode 100644 design/README.md diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5b9f521a..8f31bfc4 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -34,6 +34,7 @@ repos: hooks: - id: blacken-docs additional_dependencies: [black==24.2.0] + exclude: ^design/ - repo: local hooks: - id: rst diff --git a/design/01-module-reorganization.md b/design/01-module-reorganization.md new file mode 100644 index 00000000..819b8803 --- /dev/null +++ b/design/01-module-reorganization.md @@ -0,0 +1,99 @@ +# 01 — Module reorganization + +**Status:** Foundation step (behavior-preserving move) +**Depends on:** nothing +**Next:** [02-configuration-objects.md](02-configuration-objects.md) + +## Problem + +On `main`, hook machinery is concentrated in: + +| File | Contents today | +|------|----------------| +| [`src/pluggy/_hooks.py`](../src/pluggy/_hooks.py) | TypedDicts, markers, callers, HookImpl, HookSpec, helpers | +| [`src/pluggy/_callers.py`](../src/pluggy/_callers.py) | `_multicall`, old-style wrapper adapter | + +Later steps (Protocols, CompletionHook, typed impls) need clear module +boundaries. try-claude already performed this split. + +## Goals + +- Split by role into focused modules (try-claude layout, clearer names OK). +- Preserve import paths via re-exports from `_hooks.py` / shims. +- Zero behavior change in this step. + +## Non-goals + +- New types, CompletionHook, Protocol callers (docs 02–05). +- Copying anything from `reiterate-claude`. + +## Target design (chosen) + +Cross-check summary: + +| Branch | Layout | Notes | +|--------|--------|-------| +| `try-claude` | `_hook_config`, `_hook_markers`, `_hook_callers` (callers+impls), `_callers` | Good role split; `_hook_callers` too large; `_hook_*` + `_callers` naming clash | +| `reiterate-claude` | `_config`, `_decorators`, `_caller`, `_implementation`, `_execution` | Cleaner names; **do not copy its logic** | +| **This step** | reiterate **names** + current `main` **content** | Move-only | + +```text +src/pluggy/ + _config.py # HookspecOpts, HookimplOpts, normalize_hookimpl_opts + _decorators.py # markers, HookSpec, varnames + _caller.py # HookCaller, HookRelay, _SubsetHookCaller + _implementation.py # HookImpl + _Plugin / _HookImplFunction + _execution.py # _multicall + wrapper helpers + _hooks.py # re-exports (compat) + _callers.py # thin re-export of _execution (compat) +``` + +Name mapping from try-claude: see [DECISIONS.md](DECISIONS.md) D1. For this +step, move **current `main` code** only — do not yet port try-claude’s new +types/Protocols. + +## Reference branch / files + +```bash +# Layout inspiration only — content for step 01 is current main +git show try-claude:src/pluggy/_hook_config.py +git show try-claude:src/pluggy/_hook_markers.py +git show try-claude:src/pluggy/_hook_callers.py +git show try-claude:src/pluggy/_callers.py +git show try-claude:src/pluggy/_hooks.py +``` + +## Implementation steps + +1. Create modules; cut-and-paste from `main`. +2. Fix relative imports; avoid cycles (`TYPE_CHECKING` where needed). +3. `_hooks.py` re-exports prior public/internal names. +4. Thin-shim or delete `_callers.py` after updating internal imports to + `_execution`. +5. Verify: + +```bash +uv run pytest +uv run pre-commit run -a +``` + +Commit message: + +```text +chore(structure): split hook modules into _config, _decorators, _caller, _implementation, _execution +``` + +## Public API / back-compat + +- `from pluggy import ...` unchanged. +- `from pluggy._hooks import ...` unchanged via re-exports. + +## Tests + +- No new semantic tests; suite must stay green. + +## Done when + +- [ ] Role modules exist; `_hooks.py` is re-export layer. +- [ ] Move-only diff (no intentional behavior change). +- [ ] pytest + pre-commit green. diff --git a/design/02-configuration-objects.md b/design/02-configuration-objects.md new file mode 100644 index 00000000..c3b373ff --- /dev/null +++ b/design/02-configuration-objects.md @@ -0,0 +1,149 @@ +# 02 — Configuration objects (TypedDicts removed) + +**Status:** Replace live options encoding +**Depends on:** [01-module-reorganization.md](01-module-reorganization.md) +**Next:** [03-markers-attach-config.md](03-markers-attach-config.md) + +## Problem + +On `main`, options are `HookspecOpts` / `HookimplOpts` TypedDicts — unvalidated +dicts copied around as the live representation. try-claude introduced proper +configuration classes; those are the API. + +## Goals + +- Add `HookspecConfiguration` and `HookimplConfiguration` (`__slots__`, + `Final`, validation). +- **Remove TypedDicts from the live and public API surface.** +- Provide a **narrow pytest support shim** that accepts mapping/dict-shaped + options and converts them to configuration objects (pytest migration only). +- Export configuration classes from `pluggy`. + +## Non-goals + +- Keeping TypedDicts “for compatibility” as a dual API ([DECISIONS.md](DECISIONS.md) D4). +- Marker attachment (doc 03) — can land in the same PR if cleaner, but + conceptually next. +- `create_hookimpl` body (needs NormalImpl/WrapperImpl — doc 04); may stub + or add method signature with a TODO. + +## Target design + +```python +# src/pluggy/_config.py + +class HookspecConfiguration: + __slots__ = ("firstresult", "historic", "warn_on_impl", "warn_on_impl_args") + firstresult: Final[bool] + historic: Final[bool] + warn_on_impl: Final[Warning | None] + warn_on_impl_args: Final[Mapping[str, Warning] | None] + + def __init__(self, firstresult=False, historic=False, ...): + if historic and firstresult: + raise ValueError("cannot have a historic firstresult hook") + ... + +class HookimplConfiguration: + __slots__ = ("wrapper", "hookwrapper", "optionalhook", + "tryfirst", "trylast", "specname") + ... + # create_hookimpl added in doc 04 +``` + +Pytest support shim (name flexible — e.g. `_pytest_compat.py` or helpers in +`_config.py` marked clearly): + +```python +def hookspec_config_from_mapping(opts: Mapping[str, Any]) -> HookspecConfiguration: + """Pytest/support only: accept legacy dict-shaped options.""" + return HookspecConfiguration( + firstresult=opts.get("firstresult", False), + historic=opts.get("historic", False), + warn_on_impl=opts.get("warn_on_impl"), + warn_on_impl_args=opts.get("warn_on_impl_args"), + ) + +def hookimpl_config_from_mapping(opts: Mapping[str, Any]) -> HookimplConfiguration: + ... +``` + +Do **not** keep `TypedDict` classes in `__all__`. Do not document dicts as +the options API. Markers take kwargs that construct configuration objects +directly (doc 03). + +## Reference branch / files + +```bash +git show try-claude:src/pluggy/_hook_config.py +``` + +Port classes from try-claude; then **delete** the TypedDict definitions from +the live module (try still kept them — we go further per D4). Isolate mapping +helpers as the only dict-facing surface. + +## Implementation steps + +### Step 2.1 — Add configuration classes + +Port from try-claude `_hook_config.py` into `_config.py`. + +### Step 2.2 — Remove TypedDicts from live path + +1. Delete `HookspecOpts` / `HookimplOpts` TypedDict definitions (or move to a + private pytest-shim module if pytest tests in-tree still need the names + during transition — prefer deletion + mapping helpers). +2. Update all internal imports/usages to configuration classes. +3. Update `__init__.py` exports: add configuration classes; drop TypedDict + exports. + +### Step 2.3 — Pytest support shim + +1. Add `hookspec_config_from_mapping` / `hookimpl_config_from_mapping`. +2. Document in docstring: for pytest/support migration only, not the public + options API. +3. If pytest (downstream) needs a temporary import path, keep it private + (`pluggy._config` or `pluggy._pytest_compat`), not in `__all__`. + +### Step 2.4 — Tests + +- Validation (`historic` + `firstresult`). +- Mapping shim round-trip. +- No remaining tests that treat TypedDicts as the primary API. + +```bash +uv run pytest +uv run pre-commit run -a +``` + +Commit message: + +```text +feat(config): replace TypedDict options with Hook*Configuration classes +``` + +## Public API / back-compat + +| Before | After | +|--------|-------| +| `HookspecOpts` / `HookimplOpts` TypedDicts | **Removed** from public API | +| dict attrs on marked functions | configuration objects (doc 03) | +| — | `HookspecConfiguration` / `HookimplConfiguration` exported | +| — | private mapping shim for pytest support | + +Marker **kwargs** (`firstresult=`, `wrapper=`, …) stay — they construct +objects, they are not TypedDict literals. + +## Tests to add/update + +| File | Coverage | +|------|----------| +| `testing/test_configuration.py` | Class validation; mapping shim | +| Anything importing TypedDicts | Migrate or delete | + +## Done when + +- [ ] Configuration classes are the only live options encoding. +- [ ] TypedDicts gone from public `__all__` / docs path. +- [ ] Pytest mapping shim exists and is clearly non-API. +- [ ] pytest + pre-commit green. diff --git a/design/03-markers-attach-config.md b/design/03-markers-attach-config.md new file mode 100644 index 00000000..8cc31f4e --- /dev/null +++ b/design/03-markers-attach-config.md @@ -0,0 +1,102 @@ +# 03 — Markers attach configuration objects + +**Status:** Markers emit new types only +**Depends on:** [02-configuration-objects.md](02-configuration-objects.md) +**Next:** [04-hookimpl-wrapper-types.md](04-hookimpl-wrapper-types.md) +**Also unlocks:** [06-project-spec.md](06-project-spec.md) + +## Problem + +Markers on `main` attach dicts. After doc 02, configuration classes exist; +markers and discovery must use them exclusively. + +## Goals + +- `HookspecMarker` / `HookimplMarker` attach `HookspecConfiguration` / + `HookimplConfiguration` as `_spec` / `_impl`. +- `HookSpec` stores `config: HookspecConfiguration`. +- Manager parsing reads configuration objects only (no dict branch except + calling the pytest mapping shim if an explicit compat path is required). + +## Non-goals + +- ProjectSpec on markers (doc 06) — optional to combine. +- Impl subclass factory (doc 04). + +## Target design + +```python +def setattr_hookspec_opts(func: _F) -> _F: + config = HookspecConfiguration( + firstresult=firstresult, + historic=historic, + warn_on_impl=warn_on_impl, + warn_on_impl_args=warn_on_impl_args, + ) + setattr(func, self.project_name + "_spec", config) + return func + + +def setattr_hookimpl_opts(func: _F) -> _F: + config = HookimplConfiguration(...) + setattr(func, self.project_name + "_impl", config) + return func +``` + +Decorator kwargs unchanged. Attribute **value type** is configuration object. + +```mermaid +sequenceDiagram + participant Dev + participant Marker as HookimplMarker + participant Func as function + participant PM as PluginManager + Dev->>Marker: "@hookimpl(tryfirst=True)" + Marker->>Func: "project_impl = HookimplConfiguration" + Dev->>PM: register(plugin) + PM->>Func: getattr config + Note over PM: no dict path +``` + +## Reference branch / files + +```bash +git show try-claude:src/pluggy/_hook_markers.py +git show try-claude:src/pluggy/_manager.py +``` + +## Implementation steps + +1. Update markers to construct/attach configuration objects. +2. Update `HookSpec` and manager discovery to use `.firstresult` etc. +3. Remove any `normalize_hookimpl_opts` dict mutation on the live path. +4. Tests: attached attr is configuration instance; historic+firstresult + raises at decoration time. + +```bash +uv run pytest && uv run pre-commit run -a +``` + +Commit message: + +```text +feat(decorators): attach Hook*Configuration objects on marked functions +``` + +## Public API / back-compat + +- Decorator kwargs stable. +- Private attribute payload is now a configuration object (not a dict). +- Callers that poked dict attrs must use the pytest mapping shim or migrate. + +## Tests + +| File | Coverage | +|------|----------| +| `testing/test_configuration.py` | Attachment + validation | +| Registration / marker tests | Adapt off dict assumptions | + +## Done when + +- [ ] No marker or manager live path attaches/reads TypedDicts. +- [ ] Suite green. diff --git a/design/04-hookimpl-wrapper-types.md b/design/04-hookimpl-wrapper-types.md new file mode 100644 index 00000000..833a6863 --- /dev/null +++ b/design/04-hookimpl-wrapper-types.md @@ -0,0 +1,169 @@ +# 04 — HookImpl / WrapperImpl types + CompletionHook setup + +**Status:** Core object encoding for implementations +**Depends on:** [03-markers-attach-config.md](03-markers-attach-config.md) +**Next:** [05-hookcaller-and-execution.md](05-hookcaller-and-execution.md) + +## Problem + +On `main`, one `HookImpl` class carries bool flags (`wrapper`, `hookwrapper`) +copied from a dict. Multicall branches on those flags. try-claude introduced +real subclasses and moved wrapper setup/teardown ownership onto `WrapperImpl` +via **CompletionHook** — that encoding is the point of this series. + +## Goals + +- `HookImpl` base; `NormalImpl` and `WrapperImpl` subclasses. +- `HookimplConfiguration.create_hookimpl(...) -> NormalImpl | WrapperImpl` + (**fix try footgun:** normals must be `NormalImpl`, not bare `HookImpl`). +- Store `hookimpl_config: HookimplConfiguration` (not a dict / TypedDict). +- Move arg binding to `HookImpl._get_call_args`. +- Define `@runtime_checkable` `CompletionHook` Protocol. +- Implement `WrapperImpl.setup_and_get_completion_hook(...)`. + +## Non-goals + +- Rewiring `_multicall` / callers to dual lists (doc 05) — but this doc should + leave APIs ready so 05 is mostly wiring. +- Async `maybe_submit` (doc 07). + +## Target design + +```python +# _implementation.py (from try-claude _hook_callers.py impl section) + +@runtime_checkable +class CompletionHook(Protocol): + def __call__( + self, + result: object | list[object] | None, + exception: BaseException | None, + ) -> tuple[object | list[object] | None, BaseException | None]: ... + +class HookImpl: + function: Final[...] + argnames: Final[tuple[str, ...]] + hookimpl_config: Final[HookimplConfiguration] # not opts dict + # convenience Final bools mirrored from config OK for attribute compat + def _get_call_args(self, caller_kwargs: Mapping[str, object]) -> list[object]: ... + +class NormalImpl(HookImpl): + def __init__(..., hook_impl_config: HookimplConfiguration): + if hook_impl_config.wrapper or hook_impl_config.hookwrapper: + raise ValueError("use WrapperImpl") + super().__init__(...) + +class WrapperImpl(HookImpl): + def __init__(..., hook_impl_config: HookimplConfiguration): + if not (hook_impl_config.wrapper or hook_impl_config.hookwrapper): + raise ValueError("use NormalImpl / HookImpl for normals") + super().__init__(...) + + def setup_and_get_completion_hook( + self, hook_name: str, caller_kwargs: Mapping[str, object] + ) -> CompletionHook: + args = self._get_call_args(caller_kwargs) + if self.hookwrapper: + wrapper_gen = run_old_style_hookwrapper(self, hook_name, args) + else: + wrapper_gen = self.function(*args) + next(wrapper_gen) # setup; raise wrapfail if no yield + + def completion_hook(result, exception): + # send/throw; map StopIteration.value; see try-claude body + ... + return new_result, new_exception + + return completion_hook +``` + +Factory on config: + +```python +# _config.py +def create_hookimpl(self, plugin, plugin_name, function) -> NormalImpl | WrapperImpl: + if self.wrapper or self.hookwrapper: + return WrapperImpl(plugin, plugin_name, function, self) + return NormalImpl(plugin, plugin_name, function, self) # NOT HookImpl +``` + +```mermaid +flowchart LR + Config[HookimplConfiguration] -->|"create_hookimpl"| Decision{wrapper?} + Decision -->|no| Normal[NormalImpl] + Decision -->|yes| Wrapper[WrapperImpl] + Wrapper -->|"setup_and_get_completion_hook"| CH[CompletionHook] +``` + +## Reference branch / files + +```bash +git show try-claude:src/pluggy/_hook_callers.py # HookImpl, NormalImpl, WrapperImpl, CompletionHook +git show try-claude:src/pluggy/_hook_config.py # create_hookimpl — fix return type +git show try-claude:src/pluggy/_callers.py # run_old_style_hookwrapper +``` + +**Do not** use reiterate’s unused subclasses. + +## Implementation steps + +### Step 4.1 — Types + factory + +1. Add `NormalImpl` / `WrapperImpl` / `CompletionHook` Protocol. +2. Switch `HookImpl` to hold `HookimplConfiguration`. +3. Add `_get_call_args`. +4. Implement `create_hookimpl` returning **`NormalImpl | WrapperImpl`**. +5. Point registration at `create_hookimpl`. + +### Step 4.2 — CompletionHook setup on WrapperImpl + +Port `setup_and_get_completion_hook` from try-claude carefully (StopIteration / +RuntimeError edge cases around `#544`). + +### Step 4.3 — Interim multicall + +Until doc 05, multicall may still accept a combined list but should start +calling `setup_and_get_completion_hook` for wrappers if feasible; otherwise +keep flag path one commit and flip fully in 05. Prefer **landing CompletionHook +multicall together with caller split in 05** if interim is messy — then this +step only adds types + factory + method, with unit tests for setup/teardown +in isolation. + +### Step 4.4 — Tests + +- Factory returns correct subclass. +- Wrong config on NormalImpl/WrapperImpl raises. +- `_get_call_args` missing arg → `HookCallError`. +- Wrapper setup “did not yield” / completion replaces result/exception + (can be fuller in 05). + +```bash +uv run pytest && uv run pre-commit run -a +``` + +Commit message: + +```text +feat(implementation): add NormalImpl, WrapperImpl, and CompletionHook setup API +``` + +## Public API / back-compat + +- `HookImpl` remains importable; subclasses are additive. +- Prefer exporting `HookImpl` (and optionally subclasses) from `pluggy`. +- `CompletionHook` may stay internal or be exported — try kept it near + callers; exporting is fine if useful for typing. + +## Tests + +| File | Coverage | +|------|----------| +| New or `testing/test_hookcaller.py` | Factory + subclass invariants | +| Multicall tests | Updated in doc 05 | + +## Done when + +- [ ] `create_hookimpl` never returns bare `HookImpl` for normals. +- [ ] `WrapperImpl.setup_and_get_completion_hook` exists and matches try semantics. +- [ ] `CompletionHook` is a `@runtime_checkable` Protocol. +- [ ] Suite green. diff --git a/design/05-hookcaller-and-execution.md b/design/05-hookcaller-and-execution.md new file mode 100644 index 00000000..cd540fc9 --- /dev/null +++ b/design/05-hookcaller-and-execution.md @@ -0,0 +1,222 @@ +# 05 — Protocol callers + CompletionHook multicall + +**Status:** Critical calling / wrapping / tracing redesign +**Depends on:** [04-hookimpl-wrapper-types.md](04-hookimpl-wrapper-types.md) +**Next:** [07-async-submitter.md](07-async-submitter.md) (async wires into this) +**Related:** [06-project-spec.md](06-project-spec.md) may land in parallel + +## Problem + +On `main`, one `HookCaller` class mixes normal and historic behavior; one +`_hookimpls` list interleaves wrappers; `_multicall` branches on bool flags and +manages generator teardowns inline. Tracing wraps a single-sequence `_hookexec`. + +try-claude replaces this with: + +- `@runtime_checkable` `HookCaller` Protocol +- `NormalHookCaller` / `HistoricHookCaller` / `SubsetHookCaller` +- Split typed lists +- Dual-sequence `_multicall` driven by **CompletionHook** + +This is the critical simplification of the inner hook engine. + +## Goals + +- Protocol-based caller surface (`isinstance(x, HookCaller)` works). +- Split storage: `_normal_hookimpls: list[NormalImpl]`, + `_wrapper_hookimpls: list[WrapperImpl]`. +- Historic caller: no wrappers; call history replay unchanged in behavior. +- `_multicall(hook_name, normal_impls, wrapper_impls, caller_kwargs, firstresult, ...)` + uses CompletionHook LIFO teardown — **no** `.wrapper` flag branching. +- Update `PluginManager._hookexec` / `add_hookcall_monitoring` / + `enable_tracing` for the new signature (combine lists for before/after + callbacks if needed for back-compat of monitoring shapes). +- Keep `Result` / `TagTracer` public APIs stable. + +## Non-goals + +- Async activation details beyond accepting a `Submitter` parameter stub + (full behavior in doc 07). For this step, either thread a default + `Submitter()` or add the parameter in 07 — prefer adding the parameter + here with a no-op-friendly submitter so 07 only activates `run_async`. +- Redesigning monitoring callback *semantics* beyond signature adaptation. + +## Target design + +### HookCaller Protocol (critical) + +```python +@runtime_checkable +class HookCaller(Protocol): + @property + def name(self) -> str: ... + @property + def spec(self) -> HookSpec | None: ... + def get_hookimpls(self) -> list[HookImpl]: ... + def _add_hookimpl(self, hookimpl: HookImpl) -> None: ... + + # call / call_historic / call_extra / etc. as in try-claude +``` + +Concrete classes (not a fat base with historic flags): + +| Class | Role | +|-------|------| +| `NormalHookCaller` | Split lists; `__call__` / `call_extra` | +| `HistoricHookCaller` | `_hookimpls` + `_call_history`; rejects wrappers | +| `SubsetHookCaller` | Filtered view over another caller | + +`_insert_hookimpl_into_list` preserves `[trylast, normal, tryfirst]` ordering +per list. + +### Multicall (CompletionHook) + +```python +def _multicall( + hook_name: str, + normal_impls: Sequence[NormalImpl], # or HookImpl until typed tightened + wrapper_impls: Sequence[WrapperImpl], + caller_kwargs: Mapping[str, object], + firstresult: bool, + async_submitter: Submitter, # wire fully in doc 07 +) -> object | list[object]: + completion_hooks: list[CompletionHook] = [] + results: list[object] = [] + exception: BaseException | None = None + try: + for wrapper_impl in reversed(wrapper_impls): + completion_hooks.append( + wrapper_impl.setup_and_get_completion_hook(hook_name, caller_kwargs) + ) + for normal_impl in reversed(normal_impls): + args = normal_impl._get_call_args(caller_kwargs) + res = normal_impl.function(*args) + if res is not None: + # doc 07: maybe_submit if Awaitable + results.append(res) + if firstresult: + break + except BaseException as exc: + exception = exc + + result: object | list[object] | None + result = (results[0] if results else None) if firstresult else results + + for completion_hook in reversed(completion_hooks): + result, exception = completion_hook(result, exception) + + if exception is not None: + raise exception + return result +``` + +```mermaid +sequenceDiagram + participant Caller as NormalHookCaller + participant MC as multicall + participant W as WrapperImpl + participant N as NormalImpl + participant CH as CompletionHook + Caller->>MC: normal_impls, wrapper_impls + loop wrappers reversed + MC->>W: setup_and_get_completion_hook + W-->>MC: CompletionHook + end + loop normals reversed + MC->>N: function args + end + loop completion LIFO + MC->>CH: result, exception + CH-->>MC: result, exception + end +``` + +### Tracing / monitoring + +Adapt `add_hookcall_monitoring` traced `_hookexec` to the dual-sequence + +submitter signature. For before/after callbacks that historically received one +list, combine `[*normal_impls, *wrapper_impls]` (try-claude pattern) so +external tracers keep working. + +## Reference branch / files + +```bash +git show try-claude:src/pluggy/_hook_callers.py +git show try-claude:src/pluggy/_callers.py +git show try-claude:src/pluggy/_manager.py +git show try-claude:testing/test_hookcaller.py +git show try-claude:testing/test_multicall.py +``` + +**Authority: try-claude only.** Ignore reiterate’s adapter multicall and +class-hierarchy callers. + +## Implementation steps + +### Step 5.1 — Protocol + concrete callers + +1. Introduce `HookCaller` Protocol (`@runtime_checkable`). +2. Implement `NormalHookCaller` / `HistoricHookCaller` / `SubsetHookCaller`. +3. Split lists + `_insert_hookimpl_into_list`. +4. Manager creates the correct caller when adding specs / registering impls. +5. Keep `_HookCaller` alias if needed. + +### Step 5.2 — CompletionHook multicall + +1. Replace `_execution._multicall` with try-claude CompletionHook version. +2. Remove flag-based wrapper branching from the loop. +3. Wire `_hookexec` signature through manager + callers. + +### Step 5.3 — Tracing + +1. Update `add_hookcall_monitoring` / `enable_tracing`. +2. Preserve before/after observable behavior via combined list if needed. + +### Step 5.4 — Tests + +Port/adapt try-claude `test_hookcaller.py` / `test_multicall.py` coverage: + +- Ordering across split lists. +- Wrapper teardown order (LIFO). +- Exception propagation through completion hooks. +- Historic rejects wrappers; replay works. +- `isinstance(caller, HookCaller)` is True for concretes. +- Tracing undo / before/after still fire. + +```bash +uv run pytest && uv run pre-commit run -a +``` + +Commit message(s): + +```text +refactor(caller): Protocol-based NormalHookCaller and HistoricHookCaller with split impl lists + +refactor(execution): CompletionHook-based multicall +``` + +## Public API / back-compat + +- `HookCaller` remains the public name; it is now a Protocol (runtime + checkable). Document the change for type checkers. +- Export `HistoricHookCaller` (and optionally `NormalHookCaller`) if try did. +- Calling behavior (firstresult, wrappers old/new, historic) unchanged + observably. +- Monitoring callbacks: keep combined impl list argument shape if that is + what try-claude preserved. + +## Tests + +| File | Coverage | +|------|----------| +| `testing/test_hookcaller.py` | Port try-claude additions | +| `testing/test_multicall.py` | CompletionHook semantics | +| Tracing tests | Signature adaptation | + +## Done when + +- [ ] `HookCaller` is `@runtime_checkable` Protocol; concretes pass isinstance. +- [ ] Dual lists + dual-sequence multicall; CompletionHook LIFO teardown. +- [ ] No wrapper/normal flag branching inside multicall. +- [ ] Historic + tracing behaviors preserved. +- [ ] Suite + pre-commit green. diff --git a/design/06-project-spec.md b/design/06-project-spec.md new file mode 100644 index 00000000..96f1c2cc --- /dev/null +++ b/design/06-project-spec.md @@ -0,0 +1,104 @@ +# 06 — ProjectSpec + +**Status:** Additive project hub API +**Depends on:** [03-markers-attach-config.md](03-markers-attach-config.md) +**May parallelize with:** docs 04–05 +**Next (series):** [07-async-submitter.md](07-async-submitter.md) still depends on 05 + +## Problem + +Projects today juggle a bare `project_name` string, separately constructed +`HookspecMarker` / `HookimplMarker`, and `PluginManager(project_name)`. +try-claude’s `ProjectSpec` unifies that hub and lets markers/managers accept +`str | ProjectSpec`. + +## Goals + +- Add `ProjectSpec` with `project_name`, `.hookspec`, `.hookimpl`, + `create_plugin_manager()`, config helpers. +- Markers and `PluginManager` accept `str | ProjectSpec`. +- Export `ProjectSpec` from `pluggy`. + +## Non-goals + +- Changing the meaning of project_name matching. +- Forcing all callers to migrate off strings. + +## Target design + +```python +# src/pluggy/_project.py (port try-claude) + + +class ProjectSpec: + def __init__( + self, + project_name: str, + plugin_manager_cls: type[PluginManager] | None = None, + ) -> None: ... + + @property + def hookspec(self) -> HookspecMarker: ... + + @property + def hookimpl(self) -> HookimplMarker: ... + + def create_plugin_manager(self, **kwargs: Any) -> PluginManager: ... + + def get_hookspec_config(self, **kwargs) -> HookspecConfiguration: ... + def get_hookimpl_config(self, **kwargs) -> HookimplConfiguration: ... +``` + +Markers / manager: + +```python +def __init__(self, project_name_or_spec: str | ProjectSpec): ... + + +# PluginManager likewise; project_name becomes a property from the spec +``` + +## Reference branch / files + +```bash +git show try-claude:src/pluggy/_project.py +git show try-claude:src/pluggy/_hook_markers.py # str | ProjectSpec +git show try-claude:src/pluggy/_manager.py +git show try-claude:testing/test_project_spec.py +git show try-claude:testing/benchmark.py # ProjectSpec usage +``` + +## Implementation steps + +1. Add `_project.py` from try-claude. +2. Teach markers + `PluginManager` to accept `str | ProjectSpec`. +3. Export from `__init__.py`. +4. Port `testing/test_project_spec.py`. +5. Update benchmark if it benefits from ProjectSpec helpers. + +```bash +uv run pytest && uv run pre-commit run -a +``` + +Commit message: + +```text +feat(project): add ProjectSpec hub for markers and PluginManager +``` + +## Public API / back-compat + +- Additive: strings still work everywhere. +- New: `ProjectSpec` and dual acceptance. + +## Tests + +| File | Coverage | +|------|----------| +| `testing/test_project_spec.py` | Port from try-claude | + +## Done when + +- [ ] `ProjectSpec` exported and tested. +- [ ] String and ProjectSpec construction paths both work. +- [ ] Suite green. diff --git a/design/07-async-submitter.md b/design/07-async-submitter.md new file mode 100644 index 00000000..54598c87 --- /dev/null +++ b/design/07-async-submitter.md @@ -0,0 +1,169 @@ +# 07 — Greenlet async Submitter + +**Status:** Optional async bridge for awaitable hook results +**Depends on:** [05-hookcaller-and-execution.md](05-hookcaller-and-execution.md) +**Authority:** try-claude only (persistent Submitter — not reiterate monkeypatch) + +## Problem + +Pluggy’s multicall is synchronous. Downstream (e.g. Datasette / +[await-me-maybe](https://simonwillison.net/2020/Sep/2/await-me-maybe/)) wants +hook impls to return awaitables that are awaited when the host runs under an +async context, without rewriting the entire plugin engine as async. + +## Goals + +- Add `src/pluggy/_async.py`: `Submitter`, `maybe_submit`, `require_await`, + `run`, `async_generator_to_sync`. +- Persistent `Submitter` on `PluginManager`, threaded through `_hookexec` / + callers into `_multicall` (already parameterized in doc 05). +- After each **normal** impl call, if result is `Awaitable`, + `async_submitter.maybe_submit(res)`. +- `await pm.run_async(lambda: pm.hook.some_hook())` activates the greenlet + bridge via `Submitter.run`. +- Optional packaging: `pluggy[async] = ["greenlet"]`; testing deps include + greenlet. +- Fix try-claude footgun: `Submitter.run` must allow legitimate `None` + returns (use a sentinel). + +## Non-goals + +- Auto-await of async wrapper generators (document + `async_generator_to_sync` as a manual helper). +- Nested `run_async` (hard-fail: Submitter already active). +- Making `Submitter` a public `__all__` export unless explicitly desired + (try kept it private — keep private). + +## Target design + +```mermaid +flowchart TB + asyncioTask["asyncio task parent greenlet"] + asyncioTask --> runAsync["pm.run_async sync_func"] + runAsync --> worker["worker greenlet runs sync hook tree"] + worker --> maybe["maybe_submit awaitable"] + maybe -->|"parent.switch coro"| asyncioTask + asyncioTask -->|"await coro"| worker +``` + +### Submitter + +```python +class Submitter: + def maybe_submit(self, coro: Awaitable[_T]) -> _T | Awaitable[_T]: + """Await if active; else return awaitable unchanged (await-me-maybe).""" + + def require_await(self, coro: Awaitable[_T]) -> _T: + """Await if active; else RuntimeError.""" + + async def run(self, sync_func: Callable[[], _T]) -> _T: + """Require greenlet; run sync_func in worker greenlet; await switched coros.""" +``` + +### PluginManager + +```python +def __init__(..., async_submitter: Submitter | None = None): + self._async_submitter = async_submitter or Submitter() + +async def run_async(self, func: Callable[[], _T]) -> _T: + return await self._async_submitter.run(func) +``` + +No temporary replacement of `_inner_hookexec` for async — activation is +entirely `Submitter.run` setting `_active_submitter`. + +### Multicall integration + +```python +res = normal_impl.function(*args) +if res is not None: + if isinstance(res, Awaitable): + res = async_submitter.maybe_submit(res) + results.append(res) +``` + +## Reference branch / files + +```bash +git show try-claude:src/pluggy/_async.py +git show try-claude:src/pluggy/_callers.py # maybe_submit site +git show try-claude:src/pluggy/_manager.py # run_async, persistent submitter +git show try-claude:testing/test_async.py +git show try-claude:pyproject.toml # optional-dependencies async +``` + +**Rejected:** `reiterate-claude` ephemeral submitter + `_inner_hookexec` wrap. + +## Implementation steps + +### Step 7.1 — `_async.py` + +1. Port from try-claude. +2. Fix `None` result footgun with a sentinel. +3. Lazy-import greenlet inside `run` / helpers. + +### Step 7.2 — Packaging + +```toml +[project.optional-dependencies] +async = ["greenlet"] +``` + +Add `greenlet` (and `types-greenlet` if needed) to the testing dependency group. + +### Step 7.3 — Wire Submitter + +1. Ensure doc 05’s `_hookexec` / multicall already take `async_submitter`. +2. Store on PM; pass into callers at construction (try-claude). +3. Implement `run_async` without monkeypatching `_inner_hookexec`. + +### Step 7.4 — Tests (`testing/test_async.py`) + +Port try-claude suite; minimum: + +1. Sync-only under `run_async` +2. Mixed sync + `async def` / coroutine-returning hooks +3. Outside context: awaitable left in results (await-me-maybe) +4. Missing greenlet → clear `RuntimeError` +5. `require_await` outside context fails +6. `async_generator_to_sync` basic / send / throw / inactive +7. Nested `run_async` rejected +8. `run_async` returning `None` succeeds (footgun regression test) + +```bash +uv run pytest && uv run pre-commit run -a +``` + +Commit message: + +```text +feat(async): greenlet Submitter and PluginManager.run_async +``` + +## Public API / back-compat + +| API | Notes | +|-----|-------| +| `PluginManager.run_async` | New public method | +| `pluggy[async]` | Optional extra | +| Sync `pm.hook.x()` | Unchanged; may contain raw awaitables in results | +| Wrappers | Still sync generators; async wrappers need manual helper | +| `Submitter` | Private module | + +## Behavior matrix + +| Scenario | Behavior | +|----------|----------| +| Sync hook, sync call | Unchanged | +| Awaitable outside `run_async` | Left as awaitable (`maybe_submit` no-op) | +| Awaitable inside `run_async` | Awaited; value enters results | +| Missing greenlet | `run_async` raises | +| Nested `run_async` | Raises “already active” | + +## Done when + +- [ ] Persistent Submitter wired; no exec monkeypatch. +- [ ] Optional `[async]` extra declared. +- [ ] try-claude async tests ported + `None` return regression test. +- [ ] Suite + pre-commit green. diff --git a/design/DECISIONS.md b/design/DECISIONS.md new file mode 100644 index 00000000..c4b3cb2c --- /dev/null +++ b/design/DECISIONS.md @@ -0,0 +1,140 @@ +# Design decisions (try-claude authority) + +Experimental work on **`try-claude`** established the intended architecture. +**`reiterate-claude` was a failed experiment** that destroyed good abstractions +(unused subclasses, flag-driven multicall, CompletionHook removed, ephemeral +submitter monkeypatch, class-hierarchy callers instead of Protocols). Do **not** +copy reiterate logic. At most skim it for accidental rename ideas; never treat +it as design authority. + +**Primary reference:** `try-claude` / `origin/try-claude-backup`. + +## D1 — Module layout + +**Decision:** Split roles into focused modules. Prefer try-claude’s split, +renamed for clarity if needed: + +| try-claude | Target | +|------------|--------| +| `_hook_config.py` | `_config.py` | +| `_hook_markers.py` | `_decorators.py` | +| `_hook_callers.py` | `_caller.py` (callers + Protocol) + `_implementation.py` (HookImpl hierarchy) | +| `_callers.py` | `_execution.py` (multicall + CompletionHook orchestration) | +| `_project.py` / `_async.py` | same names | + +`_hooks.py` remains a thin re-export/compat layer where useful. + +**Rejected:** Anything from reiterate’s weakened `_execution` / `_caller` / +`_implementation` bodies. + +## D2 — HookCaller: runtime_checkable Protocols (critical) + +**Decision:** `HookCaller` is a `@runtime_checkable` `Protocol`. Concrete +callers (`NormalHookCaller`, `HistoricHookCaller`, `SubsetHookCaller`) +structurally implement it. Use Protocols elsewhere for exec/monitoring +boundaries where try-claude did (`_HookExec`, `CompletionHook`, …). + +**Rejected:** reiterate’s concrete inheritance hierarchy that erased the +interface contract. + +**Why:** Checkable protocols are how we type and isinstance-test callers +without freezing a brittle base class. This is a **critical** design point, +not optional polish. + +## D3 — CompletionHook teardown (critical) + +**Decision:** Wrappers expose teardown as `CompletionHook`: + +```python +@runtime_checkable +class CompletionHook(Protocol): + def __call__( + self, + result: object | list[object] | None, + exception: BaseException | None, + ) -> tuple[object | list[object] | None, BaseException | None]: ... +``` + +`WrapperImpl.setup_and_get_completion_hook(hook_name, caller_kwargs)` runs +setup (`next(gen)`) and returns the completion closure. Old-style wrappers +are adapted *inside* that method via `run_old_style_hookwrapper`. + +`_multicall` phases: + +1. Setup wrappers → collect `CompletionHook`s +2. Run `NormalImpl`s (arg bind via `_get_call_args`) +3. Run completion hooks LIFO; each may replace `(result, exception)` +4. Raise or return + +**Rejected:** reiterate’s “CompletionHook no longer needed” adapter + flag +dispatch inside multicall. That is the failed simplification. + +**Why:** CompletionHook is the critical enhancement that simplifies the +inner hook engine: multicall orchestrates phases; wrappers own +setup/teardown; no `.wrapper` / `.hookwrapper` branching in the hot loop. + +## D4 — New types end-to-end; TypedDicts are gone + +**Decision:** Live API uses configuration **classes** and impl **subclasses**: + +- `HookspecConfiguration` / `HookimplConfiguration` (`__slots__` + `Final`) +- `HookImpl` / `NormalImpl` / `WrapperImpl` +- `HookimplConfiguration.create_hookimpl(...) -> NormalImpl | WrapperImpl` + (fix try-claude footgun: normals must be `NormalImpl`, not bare `HookImpl`) +- Typed split lists on `NormalHookCaller`; dual-sequence `_multicall` + +**TypedDicts (`HookspecOpts` / `HookimplOpts`) are removed from the public +and internal live path.** They are not “kept for compatibility.” + +**Pytest support shim only:** a narrow compatibility helper (for pytest / +downstream that still hand-builds dict-shaped options during migration) may +accept mappings and convert them into configuration objects. That shim is +not the API; the API is the configuration classes. Do not re-export +TypedDicts as the preferred types in `__all__`. + +**Rejected:** reiterate’s unused subclasses; keeping TypedDicts as the +long-term dual API. + +## D5 — Async: persistent Submitter (try-claude) + +**Decision:** `PluginManager` owns a `Submitter`, threaded through +`_hookexec` / callers into `_multicall`. `maybe_submit` on awaitable normal +results; inactive = pass-through (await-me-maybe). +`await pm.run_async(...)` → `Submitter.run`. Optional `pluggy[async] = +["greenlet"]`. + +**Rejected:** reiterate’s ephemeral Submitter + `_inner_hookexec` monkeypatch. + +## D6 — ProjectSpec + +**Decision:** Additive hub. Markers and `PluginManager` accept +`str | ProjectSpec` (try-claude). + +## D7 — Result and tracing + +**Decision:** Keep `Result` / `TagTracer` public APIs. Update monitoring / +`_hookexec` signatures for split lists, submitter, and CompletionHook-era +multicall. Tracing callbacks may receive a combined impl list for back-compat +of the before/after hook shapes (as try-claude did). + +## D8 — Bugs to fix when porting try-claude + +1. `create_hookimpl` → return `NormalImpl` for non-wrappers. +2. `Submitter.run` → sentinel instead of `if result is None` failure. +3. Normal list typed as `list[NormalImpl]`. +4. Remove TypedDict definitions from the live API surface; isolate any dict + acceptance in an explicit pytest/support shim module or helper. + +## Reference + +```bash +git show try-claude:src/pluggy/_hook_callers.py +git show try-claude:src/pluggy/_callers.py +git show try-claude:src/pluggy/_hook_config.py +git show try-claude:src/pluggy/_async.py +git show try-claude:testing/test_async.py +git show try-claude:testing/test_hookcaller.py +git show try-claude:testing/test_project_spec.py +``` + +Do not use `reiterate-claude` as a logic source. diff --git a/design/README.md b/design/README.md new file mode 100644 index 00000000..3a8bb790 --- /dev/null +++ b/design/README.md @@ -0,0 +1,115 @@ +# Pluggy internal refactorings — design docs + +Agent-oriented design documents for re-implementing **`try-claude`** onto +`main` as a clean, ordered series of commits. + +**`reiterate-claude` was a failed experiment** — do not copy its logic. +These docs are **not** part of the published Sphinx docs. + +Read [DECISIONS.md](DECISIONS.md) before implementing anything. + +## Goals + +- **New types only:** `HookspecConfiguration` / `HookimplConfiguration`; + TypedDicts removed from the live API (pytest support shim may convert dicts). +- **Typed impls:** `NormalImpl` / `WrapperImpl` + split lists + dual-sequence + `_multicall`. +- **CompletionHook** (critical): wrappers own setup/teardown; multicall is + phase orchestration only. +- **Protocols** (critical): `@runtime_checkable` `HookCaller`, `CompletionHook`, + `_HookExec`, etc. +- **Async:** persistent greenlet `Submitter` + `PluginManager.run_async`. +- Public *behavior* stays compatible; the *encoding* of options upgrades to + objects. + +## Non-goals + +- Keeping TypedDicts as a dual long-term API. +- Adopting anything from reiterate’s destroyed abstractions. +- Redesigning `Result` / `TagTracer` public APIs. +- Auto-await of async wrapper generators in v1 async. + +## Target architecture + +| Area | Choice | +|------|--------| +| Module layout | try-claude split; optional clearer file names (`_config`, `_decorators`, `_caller`, `_implementation`, `_execution`) | +| HookCaller | `@runtime_checkable` Protocol + Normal / Historic / Subset concretes | +| Wrapping | `CompletionHook` via `WrapperImpl.setup_and_get_completion_hook` | +| Options | Configuration classes only; dict shim for pytest support only | +| Impls | `NormalImpl` / `WrapperImpl`; factory returns the right subclass | +| Async | Persistent `Submitter`; `pluggy[async]` | +| Project | `ProjectSpec`; `str \| ProjectSpec` on markers/PM | + +```mermaid +flowchart TB + subgraph markers [Markers and config] + ProjectSpec --> HookspecMarker + ProjectSpec --> HookimplMarker + HookspecMarker --> HookspecConfiguration + HookimplMarker --> HookimplConfiguration + PytestShim["pytest dict shim"] -->|"to config objects"| HookimplConfiguration + end + subgraph callers [Callers] + HookCallerProto["HookCaller Protocol"] + NormalHookCaller --> NormalList["list of NormalImpl"] + NormalHookCaller --> WrapperList["list of WrapperImpl"] + HistoricHookCaller --> HistoricList["list of NormalImpl"] + end + subgraph exec [Execution] + WrapperList -->|"setup_and_get_completion_hook"| CompletionHooks["CompletionHook LIFO"] + NormalList --> Multicall["_multicall"] + CompletionHooks --> Multicall + Submitter --> Multicall + end + PluginManager --> NormalHookCaller + PluginManager --> HistoricHookCaller + PluginManager -->|"run_async"| Submitter + HookimplConfiguration -->|"create_hookimpl"| NormalList + HookimplConfiguration -->|"create_hookimpl"| WrapperList +``` + +## Document index (implement in this order) + +| # | Document | Depends on | Summary | +|---|----------|------------|---------| +| 0 | [DECISIONS.md](DECISIONS.md) | — | Authority, Protocols, CompletionHook, TypedDict removal | +| 1 | [01-module-reorganization.md](01-module-reorganization.md) | — | Split into role modules | +| 2 | [02-configuration-objects.md](02-configuration-objects.md) | 01 | Config classes; remove TypedDicts; pytest shim | +| 3 | [03-markers-attach-config.md](03-markers-attach-config.md) | 02 | Markers attach config objects | +| 4 | [04-hookimpl-wrapper-types.md](04-hookimpl-wrapper-types.md) | 03 | NormalImpl / WrapperImpl + CompletionHook setup API | +| 5 | [05-hookcaller-and-execution.md](05-hookcaller-and-execution.md) | 04 | Protocol callers + CompletionHook multicall + tracing | +| 6 | [06-project-spec.md](06-project-spec.md) | 03 | ProjectSpec hub | +| 7 | [07-async-submitter.md](07-async-submitter.md) | 05 | Persistent Submitter + run_async | + +## Branch map + +| Branch | Role | +|--------|------| +| **`try-claude`** | **Only design authority** | +| `reiterate-claude` | Failed experiment — **do not port** | +| `etablish-claude*` | Out of scope | + +```bash +git show try-claude:src/pluggy/_hook_callers.py +git show try-claude:src/pluggy/_callers.py +git show try-claude:src/pluggy/_hook_config.py +git show try-claude:src/pluggy/_async.py +``` + +## How to assign agents + +1. Read [DECISIONS.md](DECISIONS.md). +2. One agent per doc, in order (06 may follow 03). +3. Port from `try-claude`; fix known footguns listed in D8. +4. After every step: `uv run pytest` && `uv run pre-commit run -a`. + +## Verification checklist (whole series) + +- [ ] No live TypedDict options path; pytest shim isolated if present. +- [ ] `isinstance(caller, HookCaller)` works via runtime_checkable Protocol. +- [ ] Wrappers tear down only through CompletionHook. +- [ ] `create_hookimpl` → `NormalImpl | WrapperImpl`. +- [ ] Dual-sequence multicall; no flag branching for wrapper vs normal. +- [ ] Async: persistent submitter, no exec monkeypatch. +- [ ] `uv run pytest` / `uv run pre-commit run -a` green. From 7489fdb178004e3430e57ec27a77945830a34e74 Mon Sep 17 00:00:00 2001 From: Ronny Pfannschmidt Date: Wed, 22 Jul 2026 12:24:41 +0200 Subject: [PATCH 2/3] chore(structure): split hook modules into role-specific files Move hook types, markers, callers, implementations, and multicall out of the monolithic _hooks/_callers modules so later typed-config and CompletionHook work can land without thrashing one huge file. Keep _hooks and _callers as re-export shims for import compatibility. Co-authored-by: Cursor AI Co-authored-by: Cursor Grok 4.5 --- src/pluggy/_caller.py | 309 ++++++++++++++ src/pluggy/_callers.py | 183 +------- src/pluggy/_config.py | 54 +++ src/pluggy/_decorators.py | 354 +++++++++++++++ src/pluggy/_execution.py | 174 ++++++++ src/pluggy/_hooks.py | 783 ++-------------------------------- src/pluggy/_implementation.py | 80 ++++ 7 files changed, 1027 insertions(+), 910 deletions(-) create mode 100644 src/pluggy/_caller.py create mode 100644 src/pluggy/_config.py create mode 100644 src/pluggy/_decorators.py create mode 100644 src/pluggy/_execution.py create mode 100644 src/pluggy/_implementation.py diff --git a/src/pluggy/_caller.py b/src/pluggy/_caller.py new file mode 100644 index 00000000..5569c631 --- /dev/null +++ b/src/pluggy/_caller.py @@ -0,0 +1,309 @@ +""" +Hook callers and relay. +""" + +from __future__ import annotations + +from collections.abc import Callable +from collections.abc import Mapping +from collections.abc import Sequence +from collections.abc import Set +from typing import Any +from typing import Final +from typing import final +from typing import TYPE_CHECKING +from typing import TypeAlias +import warnings + +from ._config import HookimplOpts +from ._config import HookspecOpts +from ._decorators import _Namespace +from ._decorators import HookSpec +from ._implementation import _Plugin +from ._implementation import HookImpl + + +_HookExec: TypeAlias = Callable[ + [str, Sequence[HookImpl], Mapping[str, object], bool], + object | list[object], +] + + +@final +class HookRelay: + """Hook holder object for performing 1:N hook calls where N is the number + of registered plugins.""" + + __slots__ = ("__dict__",) + + def __init__(self) -> None: + """:meta private:""" + + if TYPE_CHECKING: + + def __getattr__(self, name: str) -> HookCaller: ... + + +# Historical name (pluggy<=1.2), kept for backward compatibility. +_HookRelay = HookRelay + + +_CallHistory: TypeAlias = list[ + tuple[Mapping[str, object], Callable[[Any], None] | None] +] + + +class HookCaller: + """A caller of all registered implementations of a hook specification.""" + + __slots__ = ( + "name", + "spec", + "_hookexec", + "_hookimpls", + "_call_history", + ) + + def __init__( + self, + name: str, + hook_execute: _HookExec, + specmodule_or_class: _Namespace | None = None, + spec_opts: HookspecOpts | None = None, + ) -> None: + """:meta private:""" + #: Name of the hook getting called. + self.name: Final = name + self._hookexec: Final = hook_execute + # The hookimpls list. The caller iterates it *in reverse*. Format: + # 1. trylast nonwrappers + # 2. nonwrappers + # 3. tryfirst nonwrappers + # 4. trylast wrappers + # 5. wrappers + # 6. tryfirst wrappers + self._hookimpls: Final[list[HookImpl]] = [] + self._call_history: _CallHistory | None = None + # TODO: Document, or make private. + self.spec: HookSpec | None = None + if specmodule_or_class is not None: + assert spec_opts is not None + self.set_specification(specmodule_or_class, spec_opts) + + # TODO: Document, or make private. + def has_spec(self) -> bool: + return self.spec is not None + + # TODO: Document, or make private. + def set_specification( + self, + specmodule_or_class: _Namespace, + spec_opts: HookspecOpts, + ) -> None: + if self.spec is not None: + raise ValueError( + f"Hook {self.spec.name!r} is already registered " + f"within namespace {self.spec.namespace}" + ) + self.spec = HookSpec(specmodule_or_class, self.name, spec_opts) + if spec_opts.get("historic"): + self._call_history = [] + + def is_historic(self) -> bool: + """Whether this caller is :ref:`historic `.""" + return self._call_history is not None + + def _remove_plugin(self, plugin: _Plugin) -> None: + """Remove all hook implementations registered by the given plugin.""" + remaining = [impl for impl in self._hookimpls if impl.plugin != plugin] + if len(remaining) == len(self._hookimpls): + raise ValueError(f"plugin {plugin!r} not found") + self._hookimpls[:] = remaining + + def get_hookimpls(self) -> list[HookImpl]: + """Get all registered hook implementations for this hook.""" + return self._hookimpls.copy() + + def _add_hookimpl(self, hookimpl: HookImpl) -> None: + """Add an implementation to the callback chain.""" + for i, method in enumerate(self._hookimpls): + if method.hookwrapper or method.wrapper: + splitpoint = i + break + else: + splitpoint = len(self._hookimpls) + if hookimpl.hookwrapper or hookimpl.wrapper: + start, end = splitpoint, len(self._hookimpls) + else: + start, end = 0, splitpoint + + if hookimpl.trylast: + self._hookimpls.insert(start, hookimpl) + elif hookimpl.tryfirst: + self._hookimpls.insert(end, hookimpl) + else: + # find last non-tryfirst method + i = end - 1 + while i >= start and self._hookimpls[i].tryfirst: + i -= 1 + self._hookimpls.insert(i + 1, hookimpl) + + def __repr__(self) -> str: + return f"" + + def _verify_all_args_are_provided(self, kwargs: Mapping[str, object]) -> None: + # This is written to avoid expensive operations when not needed. + if self.spec: + for argname in self.spec.argnames: + if argname not in kwargs: + notincall = ", ".join( + repr(argname) + for argname in self.spec.argnames + # Avoid self.spec.argnames - kwargs.keys() + # it doesn't preserve order. + if argname not in kwargs.keys() + ) + warnings.warn( + f"Argument(s) {notincall} which are declared in the hookspec " + "cannot be found in this hook call", + stacklevel=2, + ) + break + + def __call__(self, **kwargs: object) -> Any: + """Call the hook. + + Only accepts keyword arguments, which should match the hook + specification. + + Returns the result(s) of calling all registered plugins, see + :ref:`calling`. + """ + assert not self.is_historic(), ( + "Cannot directly call a historic hook - use call_historic instead." + ) + self._verify_all_args_are_provided(kwargs) + firstresult = self.spec.opts.get("firstresult", False) if self.spec else False + # Copy because plugins may register other plugins during iteration (#438). + return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) + + def call_historic( + self, + result_callback: Callable[[Any], None] | None = None, + kwargs: Mapping[str, object] | None = None, + ) -> None: + """Call the hook with given ``kwargs`` for all registered plugins and + for all plugins which will be registered afterwards, see + :ref:`historic`. + + :param result_callback: + If provided, will be called for each non-``None`` result obtained + from a hook implementation. + """ + assert self._call_history is not None + kwargs = kwargs or {} + self._verify_all_args_are_provided(kwargs) + self._call_history.append((kwargs, result_callback)) + # Historizing hooks don't return results. + # Remember firstresult isn't compatible with historic. + # Copy because plugins may register other plugins during iteration (#438). + res = self._hookexec(self.name, self._hookimpls.copy(), kwargs, False) + if result_callback is None: + return + if isinstance(res, list): + for x in res: + result_callback(x) + + def call_extra( + self, methods: Sequence[Callable[..., object]], kwargs: Mapping[str, object] + ) -> Any: + """Call the hook with some additional temporarily participating + methods using the specified ``kwargs`` as call parameters, see + :ref:`call_extra`.""" + assert not self.is_historic(), ( + "Cannot directly call a historic hook - use call_historic instead." + ) + self._verify_all_args_are_provided(kwargs) + opts: HookimplOpts = { + "wrapper": False, + "hookwrapper": False, + "optionalhook": False, + "trylast": False, + "tryfirst": False, + "specname": None, + } + hookimpls = self._hookimpls.copy() + for method in methods: + hookimpl = HookImpl(None, "", method, opts) + # Find last non-tryfirst nonwrapper method. + i = len(hookimpls) - 1 + while i >= 0 and ( + # Skip wrappers. + (hookimpls[i].hookwrapper or hookimpls[i].wrapper) + # Skip tryfirst nonwrappers. + or hookimpls[i].tryfirst + ): + i -= 1 + hookimpls.insert(i + 1, hookimpl) + firstresult = self.spec.opts.get("firstresult", False) if self.spec else False + return self._hookexec(self.name, hookimpls, kwargs, firstresult) + + def _maybe_apply_history(self, method: HookImpl) -> None: + """Apply call history to a new hookimpl if it is marked as historic.""" + if self.is_historic(): + assert self._call_history is not None + for kwargs, result_callback in self._call_history: + res = self._hookexec(self.name, [method], kwargs, False) + if res and result_callback is not None: + # XXX: remember firstresult isn't compat with historic + assert isinstance(res, list) + result_callback(res[0]) + + +# Historical name (pluggy<=1.2), kept for backward compatibility. +_HookCaller = HookCaller + + +class _SubsetHookCaller(HookCaller): + """A proxy to another HookCaller which manages calls to all registered + plugins except the ones from remove_plugins.""" + + # This class is unusual: in inhertits from `HookCaller` so all of + # the *code* runs in the class, but it delegates all underlying *data* + # to the original HookCaller. + # `subset_hook_caller` used to be implemented by creating a full-fledged + # HookCaller, copying all hookimpls from the original. This had problems + # with memory leaks (#346) and historic calls (#347), which make a proxy + # approach better. + # An alternative implementation is to use a `_getattr__`/`__getattribute__` + # proxy, however that adds more overhead and is more tricky to implement. + + __slots__ = ( + "_orig", + "_remove_plugins", + ) + + def __init__(self, orig: HookCaller, remove_plugins: Set[_Plugin]) -> None: + self._orig = orig + self._remove_plugins = remove_plugins + self.name = orig.name # type: ignore[misc] + self._hookexec = orig._hookexec # type: ignore[misc] + + @property # type: ignore[misc] + def _hookimpls(self) -> list[HookImpl]: + return [ + impl + for impl in self._orig._hookimpls + if impl.plugin not in self._remove_plugins + ] + + @property + def spec(self) -> HookSpec | None: # type: ignore[override] + return self._orig.spec + + @property + def _call_history(self) -> _CallHistory | None: # type: ignore[override] + return self._orig._call_history + + def __repr__(self) -> str: + return f"<_SubsetHookCaller {self.name!r}>" diff --git a/src/pluggy/_callers.py b/src/pluggy/_callers.py index 450db1a7..716e5e34 100644 --- a/src/pluggy/_callers.py +++ b/src/pluggy/_callers.py @@ -1,174 +1,23 @@ """ -Call loop machinery +Call loop machinery. + +This module re-exports the execution engine for backward compatibility. +Prefer importing from :mod:`pluggy._execution`. """ from __future__ import annotations -from collections.abc import Generator -from collections.abc import Mapping -from collections.abc import Sequence -from typing import cast -from typing import NoReturn -from typing import TYPE_CHECKING -from typing import TypeAlias -import warnings - -from ._hooks import HookImpl -from ._result import HookCallError -from ._result import Result -from ._warnings import PluggyTeardownRaisedWarning - - -# Need to distinguish between old- and new-style hook wrappers. -# Wrapping with a tuple is the fastest type-safe way I found to do it. -Teardown: TypeAlias = Generator[None, object, object] - - -def run_old_style_hookwrapper( - hook_impl: HookImpl, hook_name: str, args: Sequence[object] -) -> Teardown: - """ - backward compatibility wrapper to run a old style hookwrapper as a wrapper - """ - if TYPE_CHECKING: - teardown = cast(Teardown, hook_impl.function(*args)) - else: - teardown = hook_impl.function(*args) - try: - next(teardown) - except StopIteration: - _raise_wrapfail(teardown, "did not yield") - try: - res = yield - result = Result(res, None) - except BaseException as exc: - result = Result(None, exc) - try: - teardown.send(result) - except StopIteration: - pass - except BaseException as e: - _warn_teardown_exception(hook_name, hook_impl, e) - raise - else: - _raise_wrapfail(teardown, "has second yield") - finally: - teardown.close() - return result.get_result() - - -def _raise_wrapfail( - wrap_controller: Generator[None, object, object], - msg: str, -) -> NoReturn: - co = wrap_controller.gi_code # type: ignore[attr-defined] - raise RuntimeError( - f"wrap_controller at {co.co_name!r} {co.co_filename}:{co.co_firstlineno} {msg}" - ) - - -def _warn_teardown_exception( - hook_name: str, hook_impl: HookImpl, e: BaseException -) -> None: - msg = ( - f"A plugin raised an exception during an old-style hookwrapper teardown.\n" - f"Plugin: {hook_impl.plugin_name}, Hook: {hook_name}\n" - f"{type(e).__name__}: {e}\n" - f"For more information see https://pluggy.readthedocs.io/en/stable/api_reference.html#pluggy.PluggyTeardownRaisedWarning" # noqa: E501 - ) - warnings.warn(PluggyTeardownRaisedWarning(msg), stacklevel=6) - - -def _multicall( - hook_name: str, - hook_impls: Sequence[HookImpl], - caller_kwargs: Mapping[str, object], - firstresult: bool, -) -> object | list[object]: - """Execute a call into multiple python functions/methods and return the - result(s). - - ``caller_kwargs`` comes from HookCaller.__call__(). - """ - __tracebackhide__ = True - results: list[object] = [] - exception = None - teardowns: list[Teardown] = [] - try: # run impl and wrapper setup functions in a loop - for hook_impl in reversed(hook_impls): - try: - args = [caller_kwargs[argname] for argname in hook_impl.argnames] - except KeyError as e: - raise HookCallError( - f"hook call must provide argument {e.args[0]!r}" - ) from e - - if hook_impl.hookwrapper: - function_gen = run_old_style_hookwrapper(hook_impl, hook_name, args) - - next(function_gen) # first yield - teardowns.append(function_gen) - - elif hook_impl.wrapper: - res = hook_impl.function(*args) - # If this cast is not valid, a type error is raised below, - # which is the desired response. - if TYPE_CHECKING: - function_gen = cast(Generator[None, object, object], res) - else: - function_gen = res - try: - next(function_gen) # first yield - except StopIteration: - _raise_wrapfail(function_gen, "did not yield") - teardowns.append(function_gen) - else: - res = hook_impl.function(*args) - if res is not None: - results.append(res) - if firstresult: # halt further impl calls - break - except BaseException as exc: - exception = exc - finally: - if firstresult: # first result hooks return a single value - result = results[0] if results else None - else: - result = results +from ._execution import _multicall +from ._execution import _raise_wrapfail +from ._execution import _warn_teardown_exception +from ._execution import run_old_style_hookwrapper +from ._execution import Teardown - # run all wrapper post-yield blocks - for teardown in reversed(teardowns): - try: - if exception is not None: - try: - teardown.throw(exception) - except RuntimeError as re: - # StopIteration from generator causes RuntimeError - # even for coroutine usage - see #544 - if ( - isinstance(exception, StopIteration) - and re.__cause__ is exception - ): - teardown.close() - continue - else: - raise - else: - teardown.send(result) - # Following is unreachable for a well behaved hook wrapper. - # Try to force finalizers otherwise postponed till GC action. - # Note: close() may raise if generator handles GeneratorExit. - teardown.close() - except StopIteration as si: - result = si.value - exception = None - continue - except BaseException as e: - exception = e - continue - _raise_wrapfail(teardown, "has second yield") - if exception is not None: - raise exception - else: - return result +__all__ = [ + "Teardown", + "run_old_style_hookwrapper", + "_raise_wrapfail", + "_warn_teardown_exception", + "_multicall", +] diff --git a/src/pluggy/_config.py b/src/pluggy/_config.py new file mode 100644 index 00000000..576a7794 --- /dev/null +++ b/src/pluggy/_config.py @@ -0,0 +1,54 @@ +""" +Configuration types for hook specifications and implementations. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TypedDict + + +class HookspecOpts(TypedDict): + """Options for a hook specification.""" + + #: Whether the hook is :ref:`first result only `. + firstresult: bool + #: Whether the hook is :ref:`historic `. + historic: bool + #: Whether the hook :ref:`warns when implemented `. + warn_on_impl: Warning | None + #: Whether the hook warns when :ref:`certain arguments are requested + #: `. + #: + #: .. versionadded:: 1.5 + warn_on_impl_args: Mapping[str, Warning] | None + + +class HookimplOpts(TypedDict): + """Options for a hook implementation.""" + + #: Whether the hook implementation is a :ref:`wrapper `. + wrapper: bool + #: Whether the hook implementation is an :ref:`old-style wrapper + #: `. + hookwrapper: bool + #: Whether validation against a hook specification is :ref:`optional + #: `. + optionalhook: bool + #: Whether to try to order this hook implementation :ref:`first + #: `. + tryfirst: bool + #: Whether to try to order this hook implementation :ref:`last + #: `. + trylast: bool + #: The name of the hook specification to match, see :ref:`specname`. + specname: str | None + + +def normalize_hookimpl_opts(opts: HookimplOpts) -> None: + opts.setdefault("tryfirst", False) + opts.setdefault("trylast", False) + opts.setdefault("wrapper", False) + opts.setdefault("hookwrapper", False) + opts.setdefault("optionalhook", False) + opts.setdefault("specname", None) diff --git a/src/pluggy/_decorators.py b/src/pluggy/_decorators.py new file mode 100644 index 00000000..b92b53a0 --- /dev/null +++ b/src/pluggy/_decorators.py @@ -0,0 +1,354 @@ +""" +Hook markers, specifications, and related helpers. +""" + +from __future__ import annotations + +from collections.abc import Callable +from collections.abc import Mapping +import inspect +import sys +import types +from types import ModuleType +from typing import Final +from typing import final +from typing import overload +from typing import TypeAlias +from typing import TypeVar +import warnings + +from ._config import HookimplOpts +from ._config import HookspecOpts + + +_F = TypeVar("_F", bound=Callable[..., object]) + +_Namespace: TypeAlias = ModuleType | type + + +@final +class HookspecMarker: + """Decorator for marking functions as hook specifications. + + Instantiate it with a project_name to get a decorator. + Calling :meth:`PluginManager.add_hookspecs` later will discover all marked + functions if the :class:`PluginManager` uses the same project name. + """ + + __slots__ = ("project_name",) + + def __init__(self, project_name: str) -> None: + self.project_name: Final = project_name + + @overload + def __call__( + self, + function: _F, + firstresult: bool = False, + historic: bool = False, + warn_on_impl: Warning | None = None, + warn_on_impl_args: Mapping[str, Warning] | None = None, + ) -> _F: ... + + @overload # noqa: F811 + def __call__( # noqa: F811 + self, + function: None = ..., + firstresult: bool = ..., + historic: bool = ..., + warn_on_impl: Warning | None = ..., + warn_on_impl_args: Mapping[str, Warning] | None = ..., + ) -> Callable[[_F], _F]: ... + + def __call__( # noqa: F811 + self, + function: _F | None = None, + firstresult: bool = False, + historic: bool = False, + warn_on_impl: Warning | None = None, + warn_on_impl_args: Mapping[str, Warning] | None = None, + ) -> _F | Callable[[_F], _F]: + """If passed a function, directly sets attributes on the function + which will make it discoverable to :meth:`PluginManager.add_hookspecs`. + + If passed no function, returns a decorator which can be applied to a + function later using the attributes supplied. + + :param firstresult: + If ``True``, the 1:N hook call (N being the number of registered + hook implementation functions) will stop at I<=N when the I'th + function returns a non-``None`` result. See :ref:`firstresult`. + + :param historic: + If ``True``, every call to the hook will be memorized and replayed + on plugins registered after the call was made. See :ref:`historic`. + + :param warn_on_impl: + If given, every implementation of this hook will trigger the given + warning. See :ref:`warn_on_impl`. + + :param warn_on_impl_args: + If given, every implementation of this hook which requests one of + the arguments in the dict will trigger the corresponding warning. + See :ref:`warn_on_impl`. + + .. versionadded:: 1.5 + """ + + def setattr_hookspec_opts(func: _F) -> _F: + if historic and firstresult: + raise ValueError("cannot have a historic firstresult hook") + opts: HookspecOpts = { + "firstresult": firstresult, + "historic": historic, + "warn_on_impl": warn_on_impl, + "warn_on_impl_args": warn_on_impl_args, + } + setattr(func, self.project_name + "_spec", opts) + return func + + if function is not None: + return setattr_hookspec_opts(function) + else: + return setattr_hookspec_opts + + +@final +class HookimplMarker: + """Decorator for marking functions as hook implementations. + + Instantiate it with a ``project_name`` to get a decorator. + Calling :meth:`PluginManager.register` later will discover all marked + functions if the :class:`PluginManager` uses the same project name. + """ + + __slots__ = ("project_name",) + + def __init__(self, project_name: str) -> None: + self.project_name: Final = project_name + + @overload + def __call__( + self, + function: _F, + hookwrapper: bool = ..., + optionalhook: bool = ..., + tryfirst: bool = ..., + trylast: bool = ..., + specname: str | None = ..., + wrapper: bool = ..., + ) -> _F: ... + + @overload # noqa: F811 + def __call__( # noqa: F811 + self, + function: None = ..., + hookwrapper: bool = ..., + optionalhook: bool = ..., + tryfirst: bool = ..., + trylast: bool = ..., + specname: str | None = ..., + wrapper: bool = ..., + ) -> Callable[[_F], _F]: ... + + def __call__( # noqa: F811 + self, + function: _F | None = None, + hookwrapper: bool = False, + optionalhook: bool = False, + tryfirst: bool = False, + trylast: bool = False, + specname: str | None = None, + wrapper: bool = False, + ) -> _F | Callable[[_F], _F]: + """If passed a function, directly sets attributes on the function + which will make it discoverable to :meth:`PluginManager.register`. + + If passed no function, returns a decorator which can be applied to a + function later using the attributes supplied. + + :param optionalhook: + If ``True``, a missing matching hook specification will not result + in an error (by default it is an error if no matching spec is + found). See :ref:`optionalhook`. + + :param tryfirst: + If ``True``, this hook implementation will run as early as possible + in the chain of N hook implementations for a specification. See + :ref:`callorder`. + + :param trylast: + If ``True``, this hook implementation will run as late as possible + in the chain of N hook implementations for a specification. See + :ref:`callorder`. + + :param wrapper: + If ``True`` ("new-style hook wrapper"), the hook implementation + needs to execute exactly one ``yield``. The code before the + ``yield`` is run early before any non-hook-wrapper function is run. + The code after the ``yield`` is run after all non-hook-wrapper + functions have run. The ``yield`` receives the result value of the + inner calls, or raises the exception of inner calls (including + earlier hook wrapper calls). The return value of the function + becomes the return value of the hook, and a raised exception becomes + the exception of the hook. See :ref:`hookwrapper`. + + :param hookwrapper: + If ``True`` ("old-style hook wrapper"), the hook implementation + needs to execute exactly one ``yield``. The code before the + ``yield`` is run early before any non-hook-wrapper function is run. + The code after the ``yield`` is run after all non-hook-wrapper + function have run The ``yield`` receives a :class:`Result` object + representing the exception or result outcome of the inner calls + (including earlier hook wrapper calls). This option is mutually + exclusive with ``wrapper``. See :ref:`old_style_hookwrapper`. + + :param specname: + If provided, the given name will be used instead of the function + name when matching this hook implementation to a hook specification + during registration. See :ref:`specname`. + + .. versionadded:: 1.2.0 + The ``wrapper`` parameter. + """ + + def setattr_hookimpl_opts(func: _F) -> _F: + opts: HookimplOpts = { + "wrapper": wrapper, + "hookwrapper": hookwrapper, + "optionalhook": optionalhook, + "tryfirst": tryfirst, + "trylast": trylast, + "specname": specname, + } + setattr(func, self.project_name + "_impl", opts) + return func + + if function is None: + return setattr_hookimpl_opts + else: + return setattr_hookimpl_opts(function) + + +_PYPY = sys.implementation.name == "pypy" +_IMPLICIT_NAMES = ("self", "cls", "obj") if _PYPY else ("self", "cls") + +# Qualnames whose missing-self deprecation warning is suppressed because +# their upstream code is already fixed but not yet released. +# Remove entries once a release with the fix is available. +_NOSELF_WARN_SUPPRESS: frozenset[str] = frozenset( + { + # pytest-timeout >=2.3.2 has the fix, but is unreleased as of 2026-05. + "TimeoutHooks.pytest_timeout_set_timer", + "TimeoutHooks.pytest_timeout_cancel_timer", + } +) + + +def varnames( + func: object, *, legacy_noself: bool = False +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Return tuple of positional and keyword parameter names for a callable. + + In case of a class, its ``__init__`` method is considered. + For bound methods, the already-bound first parameter is not included. + For unbound methods with a dotted ``__qualname__``, the first parameter is + stripped only if its name is a known implicit name (``self``, ``cls``). + Keyword-only parameters are not included. + + :param legacy_noself: + If ``True``, support hookspec classes whose methods omit ``self``. + When the function looks like a class method but has no implicit first + parameter, a :class:`DeprecationWarning` is emitted. + """ + is_bound = False + if inspect.isclass(func): + try: + func = func.__init__ + except AttributeError: # pragma: no cover - pypy special case + return (), () + is_bound = True + elif not inspect.isroutine(func): # callable object? + try: + func = getattr(func, "__call__", func) + except Exception: # pragma: no cover - pypy special case + return (), () + + # Track bound methods before unwrapping, since __func__ loses that info. + if inspect.ismethod(func): + is_bound = True + func = inspect.unwrap(func) # type: ignore[arg-type] + if inspect.ismethod(func): + is_bound = True + func = func.__func__ + + try: + code: types.CodeType = func.__code__ # type: ignore[attr-defined] + defaults: tuple[object, ...] | None = func.__defaults__ # type: ignore[attr-defined] + qualname: str = func.__qualname__ # type: ignore[attr-defined] + except AttributeError: # pragma: no cover + return (), () + + # Get positional argument names (positional-only + positional-or-keyword) + args: tuple[str, ...] = code.co_varnames[: code.co_argcount] + + # Determine which args have defaults + kwargs: tuple[str, ...] + if defaults: + index = -len(defaults) + args, kwargs = args[:index], args[index:] + else: + kwargs = () + + # Strip implicit instance/class arg. + # Check if this looks like a method defined in a class by examining the + # qualname after the last "." segment (if any). A remaining dot + # means it's a class method (e.g. "MyClass.method" or + # "func..MyClass.method"), not just a nested function. + _tail = qualname.rsplit(".", maxsplit=1)[-1] + _is_class_method = "." in _tail + if args: + if is_bound: + args = args[1:] + elif _is_class_method and args[0] in _IMPLICIT_NAMES: + args = args[1:] + elif _is_class_method and legacy_noself: + if _tail not in _NOSELF_WARN_SUPPRESS: + warnings.warn( + f"{qualname} is a method but its first parameter" + f" {args[0]!r} is not 'self'." + f" Add 'self' as the first parameter or use @staticmethod." + f" This will become an error in a future version of pluggy.", + DeprecationWarning, + stacklevel=2, + ) + + return args, kwargs + + +@final +class HookSpec: + __slots__ = ( + "namespace", + "function", + "name", + "argnames", + "kwargnames", + "opts", + "warn_on_impl", + "warn_on_impl_args", + ) + + def __init__(self, namespace: _Namespace, name: str, opts: HookspecOpts) -> None: + self.namespace = namespace + self.name = name + self.function: Callable[..., object] = getattr(namespace, name) + legacy_noself = inspect.isclass(namespace) and not isinstance( + inspect.getattr_static(namespace, name), staticmethod + ) + self.argnames, self.kwargnames = varnames( + self.function, legacy_noself=legacy_noself + ) + self.opts = opts + self.warn_on_impl = opts.get("warn_on_impl") + self.warn_on_impl_args = opts.get("warn_on_impl_args") diff --git a/src/pluggy/_execution.py b/src/pluggy/_execution.py new file mode 100644 index 00000000..a41c9e1a --- /dev/null +++ b/src/pluggy/_execution.py @@ -0,0 +1,174 @@ +""" +Hook call execution (multicall) machinery. +""" + +from __future__ import annotations + +from collections.abc import Generator +from collections.abc import Mapping +from collections.abc import Sequence +from typing import cast +from typing import NoReturn +from typing import TYPE_CHECKING +from typing import TypeAlias +import warnings + +from ._implementation import HookImpl +from ._result import HookCallError +from ._result import Result +from ._warnings import PluggyTeardownRaisedWarning + + +# Need to distinguish between old- and new-style hook wrappers. +# Wrapping with a tuple is the fastest type-safe way I found to do it. +Teardown: TypeAlias = Generator[None, object, object] + + +def run_old_style_hookwrapper( + hook_impl: HookImpl, hook_name: str, args: Sequence[object] +) -> Teardown: + """ + backward compatibility wrapper to run a old style hookwrapper as a wrapper + """ + if TYPE_CHECKING: + teardown = cast(Teardown, hook_impl.function(*args)) + else: + teardown = hook_impl.function(*args) + try: + next(teardown) + except StopIteration: + _raise_wrapfail(teardown, "did not yield") + try: + res = yield + result = Result(res, None) + except BaseException as exc: + result = Result(None, exc) + try: + teardown.send(result) + except StopIteration: + pass + except BaseException as e: + _warn_teardown_exception(hook_name, hook_impl, e) + raise + else: + _raise_wrapfail(teardown, "has second yield") + finally: + teardown.close() + return result.get_result() + + +def _raise_wrapfail( + wrap_controller: Generator[None, object, object], + msg: str, +) -> NoReturn: + co = wrap_controller.gi_code # type: ignore[attr-defined] + raise RuntimeError( + f"wrap_controller at {co.co_name!r} {co.co_filename}:{co.co_firstlineno} {msg}" + ) + + +def _warn_teardown_exception( + hook_name: str, hook_impl: HookImpl, e: BaseException +) -> None: + msg = ( + f"A plugin raised an exception during an old-style hookwrapper teardown.\n" + f"Plugin: {hook_impl.plugin_name}, Hook: {hook_name}\n" + f"{type(e).__name__}: {e}\n" + f"For more information see https://pluggy.readthedocs.io/en/stable/api_reference.html#pluggy.PluggyTeardownRaisedWarning" # noqa: E501 + ) + warnings.warn(PluggyTeardownRaisedWarning(msg), stacklevel=6) + + +def _multicall( + hook_name: str, + hook_impls: Sequence[HookImpl], + caller_kwargs: Mapping[str, object], + firstresult: bool, +) -> object | list[object]: + """Execute a call into multiple python functions/methods and return the + result(s). + + ``caller_kwargs`` comes from HookCaller.__call__(). + """ + __tracebackhide__ = True + results: list[object] = [] + exception = None + teardowns: list[Teardown] = [] + try: # run impl and wrapper setup functions in a loop + for hook_impl in reversed(hook_impls): + try: + args = [caller_kwargs[argname] for argname in hook_impl.argnames] + except KeyError as e: + raise HookCallError( + f"hook call must provide argument {e.args[0]!r}" + ) from e + + if hook_impl.hookwrapper: + function_gen = run_old_style_hookwrapper(hook_impl, hook_name, args) + + next(function_gen) # first yield + teardowns.append(function_gen) + + elif hook_impl.wrapper: + res = hook_impl.function(*args) + # If this cast is not valid, a type error is raised below, + # which is the desired response. + if TYPE_CHECKING: + function_gen = cast(Generator[None, object, object], res) + else: + function_gen = res + try: + next(function_gen) # first yield + except StopIteration: + _raise_wrapfail(function_gen, "did not yield") + teardowns.append(function_gen) + else: + res = hook_impl.function(*args) + if res is not None: + results.append(res) + if firstresult: # halt further impl calls + break + except BaseException as exc: + exception = exc + finally: + if firstresult: # first result hooks return a single value + result = results[0] if results else None + else: + result = results + + # run all wrapper post-yield blocks + for teardown in reversed(teardowns): + try: + if exception is not None: + try: + teardown.throw(exception) + except RuntimeError as re: + # StopIteration from generator causes RuntimeError + # even for coroutine usage - see #544 + if ( + isinstance(exception, StopIteration) + and re.__cause__ is exception + ): + teardown.close() + continue + else: + raise + else: + teardown.send(result) + # Following is unreachable for a well behaved hook wrapper. + # Try to force finalizers otherwise postponed till GC action. + # Note: close() may raise if generator handles GeneratorExit. + teardown.close() + except StopIteration as si: + result = si.value + exception = None + continue + except BaseException as e: + exception = e + continue + _raise_wrapfail(teardown, "has second yield") + + if exception is not None: + raise exception + else: + return result diff --git a/src/pluggy/_hooks.py b/src/pluggy/_hooks.py index f079d3b7..dab705ec 100644 --- a/src/pluggy/_hooks.py +++ b/src/pluggy/_hooks.py @@ -1,750 +1,47 @@ """ Internal hook annotation, representation and calling machinery. + +This module re-exports symbols from the role-specific modules for +backward compatibility. """ from __future__ import annotations -from collections.abc import Callable -from collections.abc import Generator -from collections.abc import Mapping -from collections.abc import Sequence -from collections.abc import Set -import inspect -import sys -import types -from types import ModuleType -from typing import Any -from typing import Final -from typing import final -from typing import overload -from typing import TYPE_CHECKING -from typing import TypeAlias -from typing import TypedDict -from typing import TypeVar -import warnings - -from ._result import Result - - -_T = TypeVar("_T") -_F = TypeVar("_F", bound=Callable[..., object]) - -_Namespace: TypeAlias = ModuleType | type -_Plugin: TypeAlias = object -_HookExec: TypeAlias = Callable[ - [str, Sequence["HookImpl"], Mapping[str, object], bool], - object | list[object], -] -_HookImplFunction: TypeAlias = Callable[..., _T | Generator[None, Result[_T], None]] - - -class HookspecOpts(TypedDict): - """Options for a hook specification.""" - - #: Whether the hook is :ref:`first result only `. - firstresult: bool - #: Whether the hook is :ref:`historic `. - historic: bool - #: Whether the hook :ref:`warns when implemented `. - warn_on_impl: Warning | None - #: Whether the hook warns when :ref:`certain arguments are requested - #: `. - #: - #: .. versionadded:: 1.5 - warn_on_impl_args: Mapping[str, Warning] | None - - -class HookimplOpts(TypedDict): - """Options for a hook implementation.""" - - #: Whether the hook implementation is a :ref:`wrapper `. - wrapper: bool - #: Whether the hook implementation is an :ref:`old-style wrapper - #: `. - hookwrapper: bool - #: Whether validation against a hook specification is :ref:`optional - #: `. - optionalhook: bool - #: Whether to try to order this hook implementation :ref:`first - #: `. - tryfirst: bool - #: Whether to try to order this hook implementation :ref:`last - #: `. - trylast: bool - #: The name of the hook specification to match, see :ref:`specname`. - specname: str | None - - -@final -class HookspecMarker: - """Decorator for marking functions as hook specifications. - - Instantiate it with a project_name to get a decorator. - Calling :meth:`PluginManager.add_hookspecs` later will discover all marked - functions if the :class:`PluginManager` uses the same project name. - """ - - __slots__ = ("project_name",) - - def __init__(self, project_name: str) -> None: - self.project_name: Final = project_name - - @overload - def __call__( - self, - function: _F, - firstresult: bool = False, - historic: bool = False, - warn_on_impl: Warning | None = None, - warn_on_impl_args: Mapping[str, Warning] | None = None, - ) -> _F: ... - - @overload # noqa: F811 - def __call__( # noqa: F811 - self, - function: None = ..., - firstresult: bool = ..., - historic: bool = ..., - warn_on_impl: Warning | None = ..., - warn_on_impl_args: Mapping[str, Warning] | None = ..., - ) -> Callable[[_F], _F]: ... - - def __call__( # noqa: F811 - self, - function: _F | None = None, - firstresult: bool = False, - historic: bool = False, - warn_on_impl: Warning | None = None, - warn_on_impl_args: Mapping[str, Warning] | None = None, - ) -> _F | Callable[[_F], _F]: - """If passed a function, directly sets attributes on the function - which will make it discoverable to :meth:`PluginManager.add_hookspecs`. - - If passed no function, returns a decorator which can be applied to a - function later using the attributes supplied. - - :param firstresult: - If ``True``, the 1:N hook call (N being the number of registered - hook implementation functions) will stop at I<=N when the I'th - function returns a non-``None`` result. See :ref:`firstresult`. - - :param historic: - If ``True``, every call to the hook will be memorized and replayed - on plugins registered after the call was made. See :ref:`historic`. - - :param warn_on_impl: - If given, every implementation of this hook will trigger the given - warning. See :ref:`warn_on_impl`. - - :param warn_on_impl_args: - If given, every implementation of this hook which requests one of - the arguments in the dict will trigger the corresponding warning. - See :ref:`warn_on_impl`. - - .. versionadded:: 1.5 - """ - - def setattr_hookspec_opts(func: _F) -> _F: - if historic and firstresult: - raise ValueError("cannot have a historic firstresult hook") - opts: HookspecOpts = { - "firstresult": firstresult, - "historic": historic, - "warn_on_impl": warn_on_impl, - "warn_on_impl_args": warn_on_impl_args, - } - setattr(func, self.project_name + "_spec", opts) - return func - - if function is not None: - return setattr_hookspec_opts(function) - else: - return setattr_hookspec_opts - - -@final -class HookimplMarker: - """Decorator for marking functions as hook implementations. - - Instantiate it with a ``project_name`` to get a decorator. - Calling :meth:`PluginManager.register` later will discover all marked - functions if the :class:`PluginManager` uses the same project name. - """ - - __slots__ = ("project_name",) - - def __init__(self, project_name: str) -> None: - self.project_name: Final = project_name - - @overload - def __call__( - self, - function: _F, - hookwrapper: bool = ..., - optionalhook: bool = ..., - tryfirst: bool = ..., - trylast: bool = ..., - specname: str | None = ..., - wrapper: bool = ..., - ) -> _F: ... - - @overload # noqa: F811 - def __call__( # noqa: F811 - self, - function: None = ..., - hookwrapper: bool = ..., - optionalhook: bool = ..., - tryfirst: bool = ..., - trylast: bool = ..., - specname: str | None = ..., - wrapper: bool = ..., - ) -> Callable[[_F], _F]: ... - - def __call__( # noqa: F811 - self, - function: _F | None = None, - hookwrapper: bool = False, - optionalhook: bool = False, - tryfirst: bool = False, - trylast: bool = False, - specname: str | None = None, - wrapper: bool = False, - ) -> _F | Callable[[_F], _F]: - """If passed a function, directly sets attributes on the function - which will make it discoverable to :meth:`PluginManager.register`. - - If passed no function, returns a decorator which can be applied to a - function later using the attributes supplied. - - :param optionalhook: - If ``True``, a missing matching hook specification will not result - in an error (by default it is an error if no matching spec is - found). See :ref:`optionalhook`. - - :param tryfirst: - If ``True``, this hook implementation will run as early as possible - in the chain of N hook implementations for a specification. See - :ref:`callorder`. - - :param trylast: - If ``True``, this hook implementation will run as late as possible - in the chain of N hook implementations for a specification. See - :ref:`callorder`. - - :param wrapper: - If ``True`` ("new-style hook wrapper"), the hook implementation - needs to execute exactly one ``yield``. The code before the - ``yield`` is run early before any non-hook-wrapper function is run. - The code after the ``yield`` is run after all non-hook-wrapper - functions have run. The ``yield`` receives the result value of the - inner calls, or raises the exception of inner calls (including - earlier hook wrapper calls). The return value of the function - becomes the return value of the hook, and a raised exception becomes - the exception of the hook. See :ref:`hookwrapper`. - - :param hookwrapper: - If ``True`` ("old-style hook wrapper"), the hook implementation - needs to execute exactly one ``yield``. The code before the - ``yield`` is run early before any non-hook-wrapper function is run. - The code after the ``yield`` is run after all non-hook-wrapper - function have run The ``yield`` receives a :class:`Result` object - representing the exception or result outcome of the inner calls - (including earlier hook wrapper calls). This option is mutually - exclusive with ``wrapper``. See :ref:`old_style_hookwrapper`. - - :param specname: - If provided, the given name will be used instead of the function - name when matching this hook implementation to a hook specification - during registration. See :ref:`specname`. - - .. versionadded:: 1.2.0 - The ``wrapper`` parameter. - """ - - def setattr_hookimpl_opts(func: _F) -> _F: - opts: HookimplOpts = { - "wrapper": wrapper, - "hookwrapper": hookwrapper, - "optionalhook": optionalhook, - "tryfirst": tryfirst, - "trylast": trylast, - "specname": specname, - } - setattr(func, self.project_name + "_impl", opts) - return func - - if function is None: - return setattr_hookimpl_opts - else: - return setattr_hookimpl_opts(function) - - -def normalize_hookimpl_opts(opts: HookimplOpts) -> None: - opts.setdefault("tryfirst", False) - opts.setdefault("trylast", False) - opts.setdefault("wrapper", False) - opts.setdefault("hookwrapper", False) - opts.setdefault("optionalhook", False) - opts.setdefault("specname", None) - - -_PYPY = sys.implementation.name == "pypy" -_IMPLICIT_NAMES = ("self", "cls", "obj") if _PYPY else ("self", "cls") - -# Qualnames whose missing-self deprecation warning is suppressed because -# their upstream code is already fixed but not yet released. -# Remove entries once a release with the fix is available. -_NOSELF_WARN_SUPPRESS: frozenset[str] = frozenset( - { - # pytest-timeout >=2.3.2 has the fix, but is unreleased as of 2026-05. - "TimeoutHooks.pytest_timeout_set_timer", - "TimeoutHooks.pytest_timeout_cancel_timer", - } -) - - -def varnames( - func: object, *, legacy_noself: bool = False -) -> tuple[tuple[str, ...], tuple[str, ...]]: - """Return tuple of positional and keyword parameter names for a callable. - - In case of a class, its ``__init__`` method is considered. - For bound methods, the already-bound first parameter is not included. - For unbound methods with a dotted ``__qualname__``, the first parameter is - stripped only if its name is a known implicit name (``self``, ``cls``). - Keyword-only parameters are not included. - - :param legacy_noself: - If ``True``, support hookspec classes whose methods omit ``self``. - When the function looks like a class method but has no implicit first - parameter, a :class:`DeprecationWarning` is emitted. - """ - is_bound = False - if inspect.isclass(func): - try: - func = func.__init__ - except AttributeError: # pragma: no cover - pypy special case - return (), () - is_bound = True - elif not inspect.isroutine(func): # callable object? - try: - func = getattr(func, "__call__", func) - except Exception: # pragma: no cover - pypy special case - return (), () - - # Track bound methods before unwrapping, since __func__ loses that info. - if inspect.ismethod(func): - is_bound = True - func = inspect.unwrap(func) # type: ignore[arg-type] - if inspect.ismethod(func): - is_bound = True - func = func.__func__ - - try: - code: types.CodeType = func.__code__ # type: ignore[attr-defined] - defaults: tuple[object, ...] | None = func.__defaults__ # type: ignore[attr-defined] - qualname: str = func.__qualname__ # type: ignore[attr-defined] - except AttributeError: # pragma: no cover - return (), () - - # Get positional argument names (positional-only + positional-or-keyword) - args: tuple[str, ...] = code.co_varnames[: code.co_argcount] - - # Determine which args have defaults - kwargs: tuple[str, ...] - if defaults: - index = -len(defaults) - args, kwargs = args[:index], args[index:] - else: - kwargs = () - - # Strip implicit instance/class arg. - # Check if this looks like a method defined in a class by examining the - # qualname after the last "." segment (if any). A remaining dot - # means it's a class method (e.g. "MyClass.method" or - # "func..MyClass.method"), not just a nested function. - _tail = qualname.rsplit(".", maxsplit=1)[-1] - _is_class_method = "." in _tail - if args: - if is_bound: - args = args[1:] - elif _is_class_method and args[0] in _IMPLICIT_NAMES: - args = args[1:] - elif _is_class_method and legacy_noself: - if _tail not in _NOSELF_WARN_SUPPRESS: - warnings.warn( - f"{qualname} is a method but its first parameter" - f" {args[0]!r} is not 'self'." - f" Add 'self' as the first parameter or use @staticmethod." - f" This will become an error in a future version of pluggy.", - DeprecationWarning, - stacklevel=2, - ) - - return args, kwargs - - -@final -class HookRelay: - """Hook holder object for performing 1:N hook calls where N is the number - of registered plugins.""" - - __slots__ = ("__dict__",) - - def __init__(self) -> None: - """:meta private:""" - - if TYPE_CHECKING: - - def __getattr__(self, name: str) -> HookCaller: ... - - -# Historical name (pluggy<=1.2), kept for backward compatibility. -_HookRelay = HookRelay - - -_CallHistory: TypeAlias = list[ - tuple[Mapping[str, object], Callable[[Any], None] | None] +from ._caller import _HookCaller +from ._caller import _HookExec +from ._caller import _HookRelay +from ._caller import _SubsetHookCaller +from ._caller import HookCaller +from ._caller import HookRelay +from ._config import HookimplOpts +from ._config import HookspecOpts +from ._config import normalize_hookimpl_opts +from ._decorators import _Namespace +from ._decorators import HookimplMarker +from ._decorators import HookSpec +from ._decorators import HookspecMarker +from ._decorators import varnames +from ._implementation import _HookImplFunction +from ._implementation import _Plugin +from ._implementation import HookImpl + + +__all__ = [ + "HookspecOpts", + "HookimplOpts", + "normalize_hookimpl_opts", + "HookspecMarker", + "HookimplMarker", + "HookSpec", + "varnames", + "HookCaller", + "HookRelay", + "_HookCaller", + "_HookRelay", + "_SubsetHookCaller", + "HookImpl", + "_HookImplFunction", + "_Namespace", + "_Plugin", + "_HookExec", ] - - -class HookCaller: - """A caller of all registered implementations of a hook specification.""" - - __slots__ = ( - "name", - "spec", - "_hookexec", - "_hookimpls", - "_call_history", - ) - - def __init__( - self, - name: str, - hook_execute: _HookExec, - specmodule_or_class: _Namespace | None = None, - spec_opts: HookspecOpts | None = None, - ) -> None: - """:meta private:""" - #: Name of the hook getting called. - self.name: Final = name - self._hookexec: Final = hook_execute - # The hookimpls list. The caller iterates it *in reverse*. Format: - # 1. trylast nonwrappers - # 2. nonwrappers - # 3. tryfirst nonwrappers - # 4. trylast wrappers - # 5. wrappers - # 6. tryfirst wrappers - self._hookimpls: Final[list[HookImpl]] = [] - self._call_history: _CallHistory | None = None - # TODO: Document, or make private. - self.spec: HookSpec | None = None - if specmodule_or_class is not None: - assert spec_opts is not None - self.set_specification(specmodule_or_class, spec_opts) - - # TODO: Document, or make private. - def has_spec(self) -> bool: - return self.spec is not None - - # TODO: Document, or make private. - def set_specification( - self, - specmodule_or_class: _Namespace, - spec_opts: HookspecOpts, - ) -> None: - if self.spec is not None: - raise ValueError( - f"Hook {self.spec.name!r} is already registered " - f"within namespace {self.spec.namespace}" - ) - self.spec = HookSpec(specmodule_or_class, self.name, spec_opts) - if spec_opts.get("historic"): - self._call_history = [] - - def is_historic(self) -> bool: - """Whether this caller is :ref:`historic `.""" - return self._call_history is not None - - def _remove_plugin(self, plugin: _Plugin) -> None: - """Remove all hook implementations registered by the given plugin.""" - remaining = [impl for impl in self._hookimpls if impl.plugin != plugin] - if len(remaining) == len(self._hookimpls): - raise ValueError(f"plugin {plugin!r} not found") - self._hookimpls[:] = remaining - - def get_hookimpls(self) -> list[HookImpl]: - """Get all registered hook implementations for this hook.""" - return self._hookimpls.copy() - - def _add_hookimpl(self, hookimpl: HookImpl) -> None: - """Add an implementation to the callback chain.""" - for i, method in enumerate(self._hookimpls): - if method.hookwrapper or method.wrapper: - splitpoint = i - break - else: - splitpoint = len(self._hookimpls) - if hookimpl.hookwrapper or hookimpl.wrapper: - start, end = splitpoint, len(self._hookimpls) - else: - start, end = 0, splitpoint - - if hookimpl.trylast: - self._hookimpls.insert(start, hookimpl) - elif hookimpl.tryfirst: - self._hookimpls.insert(end, hookimpl) - else: - # find last non-tryfirst method - i = end - 1 - while i >= start and self._hookimpls[i].tryfirst: - i -= 1 - self._hookimpls.insert(i + 1, hookimpl) - - def __repr__(self) -> str: - return f"" - - def _verify_all_args_are_provided(self, kwargs: Mapping[str, object]) -> None: - # This is written to avoid expensive operations when not needed. - if self.spec: - for argname in self.spec.argnames: - if argname not in kwargs: - notincall = ", ".join( - repr(argname) - for argname in self.spec.argnames - # Avoid self.spec.argnames - kwargs.keys() - # it doesn't preserve order. - if argname not in kwargs.keys() - ) - warnings.warn( - f"Argument(s) {notincall} which are declared in the hookspec " - "cannot be found in this hook call", - stacklevel=2, - ) - break - - def __call__(self, **kwargs: object) -> Any: - """Call the hook. - - Only accepts keyword arguments, which should match the hook - specification. - - Returns the result(s) of calling all registered plugins, see - :ref:`calling`. - """ - assert not self.is_historic(), ( - "Cannot directly call a historic hook - use call_historic instead." - ) - self._verify_all_args_are_provided(kwargs) - firstresult = self.spec.opts.get("firstresult", False) if self.spec else False - # Copy because plugins may register other plugins during iteration (#438). - return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) - - def call_historic( - self, - result_callback: Callable[[Any], None] | None = None, - kwargs: Mapping[str, object] | None = None, - ) -> None: - """Call the hook with given ``kwargs`` for all registered plugins and - for all plugins which will be registered afterwards, see - :ref:`historic`. - - :param result_callback: - If provided, will be called for each non-``None`` result obtained - from a hook implementation. - """ - assert self._call_history is not None - kwargs = kwargs or {} - self._verify_all_args_are_provided(kwargs) - self._call_history.append((kwargs, result_callback)) - # Historizing hooks don't return results. - # Remember firstresult isn't compatible with historic. - # Copy because plugins may register other plugins during iteration (#438). - res = self._hookexec(self.name, self._hookimpls.copy(), kwargs, False) - if result_callback is None: - return - if isinstance(res, list): - for x in res: - result_callback(x) - - def call_extra( - self, methods: Sequence[Callable[..., object]], kwargs: Mapping[str, object] - ) -> Any: - """Call the hook with some additional temporarily participating - methods using the specified ``kwargs`` as call parameters, see - :ref:`call_extra`.""" - assert not self.is_historic(), ( - "Cannot directly call a historic hook - use call_historic instead." - ) - self._verify_all_args_are_provided(kwargs) - opts: HookimplOpts = { - "wrapper": False, - "hookwrapper": False, - "optionalhook": False, - "trylast": False, - "tryfirst": False, - "specname": None, - } - hookimpls = self._hookimpls.copy() - for method in methods: - hookimpl = HookImpl(None, "", method, opts) - # Find last non-tryfirst nonwrapper method. - i = len(hookimpls) - 1 - while i >= 0 and ( - # Skip wrappers. - (hookimpls[i].hookwrapper or hookimpls[i].wrapper) - # Skip tryfirst nonwrappers. - or hookimpls[i].tryfirst - ): - i -= 1 - hookimpls.insert(i + 1, hookimpl) - firstresult = self.spec.opts.get("firstresult", False) if self.spec else False - return self._hookexec(self.name, hookimpls, kwargs, firstresult) - - def _maybe_apply_history(self, method: HookImpl) -> None: - """Apply call history to a new hookimpl if it is marked as historic.""" - if self.is_historic(): - assert self._call_history is not None - for kwargs, result_callback in self._call_history: - res = self._hookexec(self.name, [method], kwargs, False) - if res and result_callback is not None: - # XXX: remember firstresult isn't compat with historic - assert isinstance(res, list) - result_callback(res[0]) - - -# Historical name (pluggy<=1.2), kept for backward compatibility. -_HookCaller = HookCaller - - -class _SubsetHookCaller(HookCaller): - """A proxy to another HookCaller which manages calls to all registered - plugins except the ones from remove_plugins.""" - - # This class is unusual: in inhertits from `HookCaller` so all of - # the *code* runs in the class, but it delegates all underlying *data* - # to the original HookCaller. - # `subset_hook_caller` used to be implemented by creating a full-fledged - # HookCaller, copying all hookimpls from the original. This had problems - # with memory leaks (#346) and historic calls (#347), which make a proxy - # approach better. - # An alternative implementation is to use a `_getattr__`/`__getattribute__` - # proxy, however that adds more overhead and is more tricky to implement. - - __slots__ = ( - "_orig", - "_remove_plugins", - ) - - def __init__(self, orig: HookCaller, remove_plugins: Set[_Plugin]) -> None: - self._orig = orig - self._remove_plugins = remove_plugins - self.name = orig.name # type: ignore[misc] - self._hookexec = orig._hookexec # type: ignore[misc] - - @property # type: ignore[misc] - def _hookimpls(self) -> list[HookImpl]: - return [ - impl - for impl in self._orig._hookimpls - if impl.plugin not in self._remove_plugins - ] - - @property - def spec(self) -> HookSpec | None: # type: ignore[override] - return self._orig.spec - - @property - def _call_history(self) -> _CallHistory | None: # type: ignore[override] - return self._orig._call_history - - def __repr__(self) -> str: - return f"<_SubsetHookCaller {self.name!r}>" - - -@final -class HookImpl: - """A hook implementation in a :class:`HookCaller`.""" - - __slots__ = ( - "function", - "argnames", - "kwargnames", - "plugin", - "opts", - "plugin_name", - "wrapper", - "hookwrapper", - "optionalhook", - "tryfirst", - "trylast", - ) - - def __init__( - self, - plugin: _Plugin, - plugin_name: str, - function: _HookImplFunction[object], - hook_impl_opts: HookimplOpts, - ) -> None: - """:meta private:""" - #: The hook implementation function. - self.function: Final = function - argnames, kwargnames = varnames(self.function) - #: The positional parameter names of ``function```. - self.argnames: Final = argnames - #: The keyword parameter names of ``function```. - self.kwargnames: Final = kwargnames - #: The plugin which defined this hook implementation. - self.plugin: Final = plugin - #: The :class:`HookimplOpts` used to configure this hook implementation. - self.opts: Final = hook_impl_opts - #: The name of the plugin which defined this hook implementation. - self.plugin_name: Final = plugin_name - #: Whether the hook implementation is a :ref:`wrapper `. - self.wrapper: Final = hook_impl_opts["wrapper"] - #: Whether the hook implementation is an :ref:`old-style wrapper - #: `. - self.hookwrapper: Final = hook_impl_opts["hookwrapper"] - #: Whether validation against a hook specification is :ref:`optional - #: `. - self.optionalhook: Final = hook_impl_opts["optionalhook"] - #: Whether to try to order this hook implementation :ref:`first - #: `. - self.tryfirst: Final = hook_impl_opts["tryfirst"] - #: Whether to try to order this hook implementation :ref:`last - #: `. - self.trylast: Final = hook_impl_opts["trylast"] - - def __repr__(self) -> str: - return f"" - - -@final -class HookSpec: - __slots__ = ( - "namespace", - "function", - "name", - "argnames", - "kwargnames", - "opts", - "warn_on_impl", - "warn_on_impl_args", - ) - - def __init__(self, namespace: _Namespace, name: str, opts: HookspecOpts) -> None: - self.namespace = namespace - self.name = name - self.function: Callable[..., object] = getattr(namespace, name) - legacy_noself = inspect.isclass(namespace) and not isinstance( - inspect.getattr_static(namespace, name), staticmethod - ) - self.argnames, self.kwargnames = varnames( - self.function, legacy_noself=legacy_noself - ) - self.opts = opts - self.warn_on_impl = opts.get("warn_on_impl") - self.warn_on_impl_args = opts.get("warn_on_impl_args") diff --git a/src/pluggy/_implementation.py b/src/pluggy/_implementation.py new file mode 100644 index 00000000..19cb91ff --- /dev/null +++ b/src/pluggy/_implementation.py @@ -0,0 +1,80 @@ +""" +Hook implementation representation. +""" + +from __future__ import annotations + +from collections.abc import Callable +from collections.abc import Generator +from typing import Final +from typing import final +from typing import TypeAlias +from typing import TypeVar + +from ._config import HookimplOpts +from ._decorators import varnames +from ._result import Result + + +_T = TypeVar("_T") + +_Plugin: TypeAlias = object +_HookImplFunction: TypeAlias = Callable[..., _T | Generator[None, Result[_T], None]] + + +@final +class HookImpl: + """A hook implementation in a :class:`HookCaller`.""" + + __slots__ = ( + "function", + "argnames", + "kwargnames", + "plugin", + "opts", + "plugin_name", + "wrapper", + "hookwrapper", + "optionalhook", + "tryfirst", + "trylast", + ) + + def __init__( + self, + plugin: _Plugin, + plugin_name: str, + function: _HookImplFunction[object], + hook_impl_opts: HookimplOpts, + ) -> None: + """:meta private:""" + #: The hook implementation function. + self.function: Final = function + argnames, kwargnames = varnames(self.function) + #: The positional parameter names of ``function```. + self.argnames: Final = argnames + #: The keyword parameter names of ``function```. + self.kwargnames: Final = kwargnames + #: The plugin which defined this hook implementation. + self.plugin: Final = plugin + #: The :class:`HookimplOpts` used to configure this hook implementation. + self.opts: Final = hook_impl_opts + #: The name of the plugin which defined this hook implementation. + self.plugin_name: Final = plugin_name + #: Whether the hook implementation is a :ref:`wrapper `. + self.wrapper: Final = hook_impl_opts["wrapper"] + #: Whether the hook implementation is an :ref:`old-style wrapper + #: `. + self.hookwrapper: Final = hook_impl_opts["hookwrapper"] + #: Whether validation against a hook specification is :ref:`optional + #: `. + self.optionalhook: Final = hook_impl_opts["optionalhook"] + #: Whether to try to order this hook implementation :ref:`first + #: `. + self.tryfirst: Final = hook_impl_opts["tryfirst"] + #: Whether to try to order this hook implementation :ref:`last + #: `. + self.trylast: Final = hook_impl_opts["trylast"] + + def __repr__(self) -> str: + return f"" From 6993f1079498e547d441f141822b90cc6535debf Mon Sep 17 00:00:00 2001 From: Ronny Pfannschmidt Date: Wed, 22 Jul 2026 14:40:06 +0200 Subject: [PATCH 3/3] feat(config): replace TypedDict options with Hook*Configuration Markers attach HookspecConfiguration/HookimplConfiguration objects. Registration discovers those privately; parse_hookimpl_opts and parse_hookspec_opts remain a deprecated pytest concession that returns legacy dicts and is only called when a subclass overrides them and no modern configuration attribute was found. Co-authored-by: Cursor AI Co-authored-by: Cursor Grok 4.5 --- changelog/704.removal.rst | 8 + docs/api_reference.rst | 6 +- docs/index.rst | 9 +- src/pluggy/__init__.py | 8 +- src/pluggy/_caller.py | 23 +-- src/pluggy/_config.py | 207 +++++++++++++++++++------ src/pluggy/_decorators.py | 46 +++--- src/pluggy/_hooks.py | 10 +- src/pluggy/_implementation.py | 17 ++- src/pluggy/_manager.py | 159 ++++++++++++++------ src/pluggy/_pytest_compat.py | 55 +++++++ testing/test_configuration.py | 276 ++++++++++++++++++++++++++++++++++ testing/test_details.py | 9 +- testing/test_hookcaller.py | 8 +- 14 files changed, 681 insertions(+), 160 deletions(-) create mode 100644 changelog/704.removal.rst create mode 100644 src/pluggy/_pytest_compat.py create mode 100644 testing/test_configuration.py diff --git a/changelog/704.removal.rst b/changelog/704.removal.rst new file mode 100644 index 00000000..4d5eef43 --- /dev/null +++ b/changelog/704.removal.rst @@ -0,0 +1,8 @@ +Hook options are now :class:`pluggy.HookspecConfiguration` / +:class:`pluggy.HookimplConfiguration` objects (markers attach these instead of +dicts). ``PluginManager.parse_hookimpl_opts`` / +``parse_hookspec_opts`` remain as a deprecated pytest/support concession that +returns legacy dicts and are only invoked during registration when a subclass +overrides them and no modern configuration attribute was found. +``HookspecOpts`` / ``HookimplOpts`` TypedDicts remain importable for +pytest/typing compatibility. diff --git a/docs/api_reference.rst b/docs/api_reference.rst index b14d725d..7d19a4a6 100644 --- a/docs/api_reference.rst +++ b/docs/api_reference.rst @@ -40,12 +40,10 @@ API Reference .. autoclass:: pluggy.HookImpl() :members: -.. autoclass:: pluggy.HookspecOpts() - :show-inheritance: +.. autoclass:: pluggy.HookspecConfiguration() :members: -.. autoclass:: pluggy.HookimplOpts() - :show-inheritance: +.. autoclass:: pluggy.HookimplConfiguration() :members: diff --git a/docs/index.rst b/docs/index.rst index b56278ed..1f1292ae 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -767,10 +767,13 @@ and particular plugins in it: Parsing mark options ^^^^^^^^^^^^^^^^^^^^ -You can retrieve the *options* applied to a particular -*hookspec* or *hookimpl* as per :ref:`marking_hooks` using the +Markers attach :class:`~pluggy.HookspecConfiguration` / +:class:`~pluggy.HookimplConfiguration` objects to functions. The :py:meth:`~pluggy.PluginManager.parse_hookspec_opts()` and -:py:meth:`~pluggy.PluginManager.parse_hookimpl_opts()` respectively. +:py:meth:`~pluggy.PluginManager.parse_hookimpl_opts()` methods remain as a +**deprecated** pytest/support concession that returns legacy dict-shaped +options; registration only calls them when a subclass overrides them and no +modern configuration attribute was found. .. _calling: diff --git a/src/pluggy/__init__.py b/src/pluggy/__init__.py index 3d81d0a3..ba9ed05d 100644 --- a/src/pluggy/__init__.py +++ b/src/pluggy/__init__.py @@ -4,6 +4,8 @@ "PluginValidationError", "HookCaller", "HookCallError", + "HookspecConfiguration", + "HookimplConfiguration", "HookspecOpts", "HookimplOpts", "HookImpl", @@ -14,15 +16,17 @@ "PluggyWarning", "PluggyTeardownRaisedWarning", ] +from ._config import HookimplConfiguration +from ._config import HookspecConfiguration from ._hooks import HookCaller from ._hooks import HookImpl from ._hooks import HookimplMarker -from ._hooks import HookimplOpts from ._hooks import HookRelay from ._hooks import HookspecMarker -from ._hooks import HookspecOpts from ._manager import PluginManager from ._manager import PluginValidationError +from ._pytest_compat import HookimplOpts +from ._pytest_compat import HookspecOpts from ._result import HookCallError from ._result import Result from ._warnings import PluggyTeardownRaisedWarning diff --git a/src/pluggy/_caller.py b/src/pluggy/_caller.py index 5569c631..10f61043 100644 --- a/src/pluggy/_caller.py +++ b/src/pluggy/_caller.py @@ -15,8 +15,8 @@ from typing import TypeAlias import warnings -from ._config import HookimplOpts -from ._config import HookspecOpts +from ._config import HookimplConfiguration +from ._config import HookspecConfiguration from ._decorators import _Namespace from ._decorators import HookSpec from ._implementation import _Plugin @@ -69,7 +69,7 @@ def __init__( name: str, hook_execute: _HookExec, specmodule_or_class: _Namespace | None = None, - spec_opts: HookspecOpts | None = None, + spec_opts: HookspecConfiguration | None = None, ) -> None: """:meta private:""" #: Name of the hook getting called. @@ -98,7 +98,7 @@ def has_spec(self) -> bool: def set_specification( self, specmodule_or_class: _Namespace, - spec_opts: HookspecOpts, + spec_opts: HookspecConfiguration, ) -> None: if self.spec is not None: raise ValueError( @@ -106,7 +106,7 @@ def set_specification( f"within namespace {self.spec.namespace}" ) self.spec = HookSpec(specmodule_or_class, self.name, spec_opts) - if spec_opts.get("historic"): + if spec_opts.historic: self._call_history = [] def is_historic(self) -> bool: @@ -183,7 +183,7 @@ def __call__(self, **kwargs: object) -> Any: "Cannot directly call a historic hook - use call_historic instead." ) self._verify_all_args_are_provided(kwargs) - firstresult = self.spec.opts.get("firstresult", False) if self.spec else False + firstresult = self.spec.opts.firstresult if self.spec else False # Copy because plugins may register other plugins during iteration (#438). return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) @@ -224,14 +224,7 @@ def call_extra( "Cannot directly call a historic hook - use call_historic instead." ) self._verify_all_args_are_provided(kwargs) - opts: HookimplOpts = { - "wrapper": False, - "hookwrapper": False, - "optionalhook": False, - "trylast": False, - "tryfirst": False, - "specname": None, - } + opts = HookimplConfiguration() hookimpls = self._hookimpls.copy() for method in methods: hookimpl = HookImpl(None, "", method, opts) @@ -245,7 +238,7 @@ def call_extra( ): i -= 1 hookimpls.insert(i + 1, hookimpl) - firstresult = self.spec.opts.get("firstresult", False) if self.spec else False + firstresult = self.spec.opts.firstresult if self.spec else False return self._hookexec(self.name, hookimpls, kwargs, firstresult) def _maybe_apply_history(self, method: HookImpl) -> None: diff --git a/src/pluggy/_config.py b/src/pluggy/_config.py index 576a7794..43eef7c6 100644 --- a/src/pluggy/_config.py +++ b/src/pluggy/_config.py @@ -5,50 +5,163 @@ from __future__ import annotations from collections.abc import Mapping -from typing import TypedDict - - -class HookspecOpts(TypedDict): - """Options for a hook specification.""" - - #: Whether the hook is :ref:`first result only `. - firstresult: bool - #: Whether the hook is :ref:`historic `. - historic: bool - #: Whether the hook :ref:`warns when implemented `. - warn_on_impl: Warning | None - #: Whether the hook warns when :ref:`certain arguments are requested - #: `. - #: - #: .. versionadded:: 1.5 - warn_on_impl_args: Mapping[str, Warning] | None - - -class HookimplOpts(TypedDict): - """Options for a hook implementation.""" - - #: Whether the hook implementation is a :ref:`wrapper `. - wrapper: bool - #: Whether the hook implementation is an :ref:`old-style wrapper - #: `. - hookwrapper: bool - #: Whether validation against a hook specification is :ref:`optional - #: `. - optionalhook: bool - #: Whether to try to order this hook implementation :ref:`first - #: `. - tryfirst: bool - #: Whether to try to order this hook implementation :ref:`last - #: `. - trylast: bool - #: The name of the hook specification to match, see :ref:`specname`. - specname: str | None - - -def normalize_hookimpl_opts(opts: HookimplOpts) -> None: - opts.setdefault("tryfirst", False) - opts.setdefault("trylast", False) - opts.setdefault("wrapper", False) - opts.setdefault("hookwrapper", False) - opts.setdefault("optionalhook", False) - opts.setdefault("specname", None) +from typing import Any +from typing import Final +from typing import final + + +@final +class HookspecConfiguration: + """Configuration for a hook specification.""" + + __slots__ = ( + "firstresult", + "historic", + "warn_on_impl", + "warn_on_impl_args", + ) + firstresult: Final[bool] + historic: Final[bool] + warn_on_impl: Final[Warning | None] + warn_on_impl_args: Final[Mapping[str, Warning] | None] + + def __init__( + self, + firstresult: bool = False, + historic: bool = False, + warn_on_impl: Warning | None = None, + warn_on_impl_args: Mapping[str, Warning] | None = None, + ) -> None: + if historic and firstresult: + raise ValueError("cannot have a historic firstresult hook") + #: Whether the hook is :ref:`first result only `. + self.firstresult = firstresult + #: Whether the hook is :ref:`historic `. + self.historic = historic + #: Whether the hook :ref:`warns when implemented `. + self.warn_on_impl = warn_on_impl + #: Whether the hook warns when :ref:`certain arguments are requested + #: `. + self.warn_on_impl_args = warn_on_impl_args + + def __repr__(self) -> str: + attrs = [ + f"{slot}={getattr(self, slot)!r}" + for slot in self.__slots__ + if getattr(self, slot) + ] + return f"HookspecConfiguration({', '.join(attrs)})" + + +@final +class HookimplConfiguration: + """Configuration for a hook implementation.""" + + __slots__ = ( + "wrapper", + "hookwrapper", + "optionalhook", + "tryfirst", + "trylast", + "specname", + ) + wrapper: Final[bool] + hookwrapper: Final[bool] + optionalhook: Final[bool] + tryfirst: Final[bool] + trylast: Final[bool] + specname: Final[str | None] + + def __init__( + self, + wrapper: bool = False, + hookwrapper: bool = False, + optionalhook: bool = False, + tryfirst: bool = False, + trylast: bool = False, + specname: str | None = None, + ) -> None: + #: Whether the hook implementation is a :ref:`wrapper `. + self.wrapper = wrapper + #: Whether the hook implementation is an :ref:`old-style wrapper + #: `. + self.hookwrapper = hookwrapper + #: Whether validation against a hook specification is :ref:`optional + #: `. + self.optionalhook = optionalhook + #: Whether to try to order this hook implementation :ref:`first + #: `. + self.tryfirst = tryfirst + #: Whether to try to order this hook implementation :ref:`last + #: `. + self.trylast = trylast + #: The name of the hook specification to match, see :ref:`specname`. + self.specname = specname + + def __repr__(self) -> str: + attrs = [ + f"{slot}={getattr(self, slot)!r}" + for slot in self.__slots__ + if getattr(self, slot) + ] + return f"HookimplConfiguration({', '.join(attrs)})" + + +def hookspec_config_from_mapping( + opts: Mapping[str, Any], +) -> HookspecConfiguration: + """Build a :class:`HookspecConfiguration` from a mapping. + + Intended for pytest/support migration only — not the public options API. + Prefer constructing :class:`HookspecConfiguration` directly. + """ + return HookspecConfiguration( + firstresult=bool(opts.get("firstresult", False)), + historic=bool(opts.get("historic", False)), + warn_on_impl=opts.get("warn_on_impl"), + warn_on_impl_args=opts.get("warn_on_impl_args"), + ) + + +def hookimpl_config_from_mapping( + opts: Mapping[str, Any], +) -> HookimplConfiguration: + """Build a :class:`HookimplConfiguration` from a mapping. + + Intended for pytest/support migration only — not the public options API. + Prefer constructing :class:`HookimplConfiguration` directly. + """ + return HookimplConfiguration( + wrapper=bool(opts.get("wrapper", False)), + hookwrapper=bool(opts.get("hookwrapper", False)), + optionalhook=bool(opts.get("optionalhook", False)), + tryfirst=bool(opts.get("tryfirst", False)), + trylast=bool(opts.get("trylast", False)), + specname=opts.get("specname"), + ) + + +def hookspec_config_to_mapping( + config: HookspecConfiguration, +) -> dict[str, Any]: + """Serialize configuration to a legacy mapping (pytest/support only).""" + return { + "firstresult": config.firstresult, + "historic": config.historic, + "warn_on_impl": config.warn_on_impl, + "warn_on_impl_args": config.warn_on_impl_args, + } + + +def hookimpl_config_to_mapping( + config: HookimplConfiguration, +) -> dict[str, Any]: + """Serialize configuration to a legacy mapping (pytest/support only).""" + return { + "wrapper": config.wrapper, + "hookwrapper": config.hookwrapper, + "optionalhook": config.optionalhook, + "tryfirst": config.tryfirst, + "trylast": config.trylast, + "specname": config.specname, + } diff --git a/src/pluggy/_decorators.py b/src/pluggy/_decorators.py index b92b53a0..347c70ad 100644 --- a/src/pluggy/_decorators.py +++ b/src/pluggy/_decorators.py @@ -17,8 +17,8 @@ from typing import TypeVar import warnings -from ._config import HookimplOpts -from ._config import HookspecOpts +from ._config import HookimplConfiguration +from ._config import HookspecConfiguration _F = TypeVar("_F", bound=Callable[..., object]) @@ -96,15 +96,13 @@ def __call__( # noqa: F811 """ def setattr_hookspec_opts(func: _F) -> _F: - if historic and firstresult: - raise ValueError("cannot have a historic firstresult hook") - opts: HookspecOpts = { - "firstresult": firstresult, - "historic": historic, - "warn_on_impl": warn_on_impl, - "warn_on_impl_args": warn_on_impl_args, - } - setattr(func, self.project_name + "_spec", opts) + config = HookspecConfiguration( + firstresult=firstresult, + historic=historic, + warn_on_impl=warn_on_impl, + warn_on_impl_args=warn_on_impl_args, + ) + setattr(func, self.project_name + "_spec", config) return func if function is not None: @@ -213,15 +211,15 @@ def __call__( # noqa: F811 """ def setattr_hookimpl_opts(func: _F) -> _F: - opts: HookimplOpts = { - "wrapper": wrapper, - "hookwrapper": hookwrapper, - "optionalhook": optionalhook, - "tryfirst": tryfirst, - "trylast": trylast, - "specname": specname, - } - setattr(func, self.project_name + "_impl", opts) + config = HookimplConfiguration( + wrapper=wrapper, + hookwrapper=hookwrapper, + optionalhook=optionalhook, + tryfirst=tryfirst, + trylast=trylast, + specname=specname, + ) + setattr(func, self.project_name + "_impl", config) return func if function is None: @@ -339,7 +337,9 @@ class HookSpec: "warn_on_impl_args", ) - def __init__(self, namespace: _Namespace, name: str, opts: HookspecOpts) -> None: + def __init__( + self, namespace: _Namespace, name: str, opts: HookspecConfiguration + ) -> None: self.namespace = namespace self.name = name self.function: Callable[..., object] = getattr(namespace, name) @@ -350,5 +350,5 @@ def __init__(self, namespace: _Namespace, name: str, opts: HookspecOpts) -> None self.function, legacy_noself=legacy_noself ) self.opts = opts - self.warn_on_impl = opts.get("warn_on_impl") - self.warn_on_impl_args = opts.get("warn_on_impl_args") + self.warn_on_impl = opts.warn_on_impl + self.warn_on_impl_args = opts.warn_on_impl_args diff --git a/src/pluggy/_hooks.py b/src/pluggy/_hooks.py index dab705ec..721c58b9 100644 --- a/src/pluggy/_hooks.py +++ b/src/pluggy/_hooks.py @@ -13,9 +13,8 @@ from ._caller import _SubsetHookCaller from ._caller import HookCaller from ._caller import HookRelay -from ._config import HookimplOpts -from ._config import HookspecOpts -from ._config import normalize_hookimpl_opts +from ._config import HookimplConfiguration +from ._config import HookspecConfiguration from ._decorators import _Namespace from ._decorators import HookimplMarker from ._decorators import HookSpec @@ -27,9 +26,8 @@ __all__ = [ - "HookspecOpts", - "HookimplOpts", - "normalize_hookimpl_opts", + "HookspecConfiguration", + "HookimplConfiguration", "HookspecMarker", "HookimplMarker", "HookSpec", diff --git a/src/pluggy/_implementation.py b/src/pluggy/_implementation.py index 19cb91ff..b631be01 100644 --- a/src/pluggy/_implementation.py +++ b/src/pluggy/_implementation.py @@ -11,7 +11,7 @@ from typing import TypeAlias from typing import TypeVar -from ._config import HookimplOpts +from ._config import HookimplConfiguration from ._decorators import varnames from ._result import Result @@ -45,7 +45,7 @@ def __init__( plugin: _Plugin, plugin_name: str, function: _HookImplFunction[object], - hook_impl_opts: HookimplOpts, + hook_impl_opts: HookimplConfiguration, ) -> None: """:meta private:""" #: The hook implementation function. @@ -57,24 +57,25 @@ def __init__( self.kwargnames: Final = kwargnames #: The plugin which defined this hook implementation. self.plugin: Final = plugin - #: The :class:`HookimplOpts` used to configure this hook implementation. + #: The :class:`HookimplConfiguration` used to configure this hook + #: implementation. self.opts: Final = hook_impl_opts #: The name of the plugin which defined this hook implementation. self.plugin_name: Final = plugin_name #: Whether the hook implementation is a :ref:`wrapper `. - self.wrapper: Final = hook_impl_opts["wrapper"] + self.wrapper: Final = hook_impl_opts.wrapper #: Whether the hook implementation is an :ref:`old-style wrapper #: `. - self.hookwrapper: Final = hook_impl_opts["hookwrapper"] + self.hookwrapper: Final = hook_impl_opts.hookwrapper #: Whether validation against a hook specification is :ref:`optional #: `. - self.optionalhook: Final = hook_impl_opts["optionalhook"] + self.optionalhook: Final = hook_impl_opts.optionalhook #: Whether to try to order this hook implementation :ref:`first #: `. - self.tryfirst: Final = hook_impl_opts["tryfirst"] + self.tryfirst: Final = hook_impl_opts.tryfirst #: Whether to try to order this hook implementation :ref:`last #: `. - self.trylast: Final = hook_impl_opts["trylast"] + self.trylast: Final = hook_impl_opts.trylast def __repr__(self) -> str: return f"" diff --git a/src/pluggy/_manager.py b/src/pluggy/_manager.py index 426e0a3b..e5c19092 100644 --- a/src/pluggy/_manager.py +++ b/src/pluggy/_manager.py @@ -15,16 +15,21 @@ from . import _tracing from ._callers import _multicall +from ._config import hookimpl_config_from_mapping +from ._config import hookimpl_config_to_mapping +from ._config import HookimplConfiguration +from ._config import hookspec_config_from_mapping +from ._config import hookspec_config_to_mapping +from ._config import HookspecConfiguration from ._hooks import _HookImplFunction from ._hooks import _Namespace from ._hooks import _Plugin from ._hooks import _SubsetHookCaller from ._hooks import HookCaller from ._hooks import HookImpl -from ._hooks import HookimplOpts from ._hooks import HookRelay -from ._hooks import HookspecOpts -from ._hooks import normalize_hookimpl_opts +from ._pytest_compat import HookimplOpts +from ._pytest_compat import HookspecOpts from ._result import Result @@ -142,12 +147,11 @@ def register(self, plugin: _Plugin, name: str | None = None) -> str | None: # register matching hook implementations of the plugin for name in dir(plugin): - hookimpl_opts = self.parse_hookimpl_opts(plugin, name) - if hookimpl_opts is not None: - normalize_hookimpl_opts(hookimpl_opts) + hookimpl_config = self._discover_hookimpl_configuration(plugin, name) + if hookimpl_config is not None: method: _HookImplFunction[object] = getattr(plugin, name) - hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_opts) - name = hookimpl_opts.get("specname") or name + hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_config) + name = hookimpl_config.specname or name hook: HookCaller | None = getattr(self.hook, name, None) if hook is None: hook = HookCaller(name, self._hookexec) @@ -158,30 +162,61 @@ def register(self, plugin: _Plugin, name: str | None = None) -> str | None: hook._add_hookimpl(hookimpl) return plugin_name - def parse_hookimpl_opts(self, plugin: _Plugin, name: str) -> HookimplOpts | None: - """Try to obtain a hook implementation from an item with the given name - in the given plugin which is being searched for hook impls. - - :returns: - The parsed hookimpl options, or None to skip the given item. - - This method can be overridden by ``PluginManager`` subclasses to - customize how hook implementation are picked up. By default, returns the - options for items decorated with :class:`HookimplMarker`. - """ - method: object = getattr(plugin, name) + def _read_hookimpl_configuration( + self, plugin: _Plugin, name: str + ) -> HookimplConfiguration | None: + """Read a modern :class:`HookimplConfiguration` from a plugin attribute.""" + try: + method: object = getattr(plugin, name) + except Exception: + # dir() can include properties that are not safely readable yet + # (e.g. pytest Config during early registration). + return None if not inspect.isroutine(method): return None try: - res: HookimplOpts | None = getattr( - method, self.project_name + "_impl", None - ) + res: object = getattr(method, self.project_name + "_impl", None) except Exception: # pragma: no cover - res = {} # type: ignore[assignment] #pragma: no cover - if res is not None and not isinstance(res, dict): - # false positive - res = None # type:ignore[unreachable] #pragma: no cover - return res + return None + if isinstance(res, HookimplConfiguration): + return res + if isinstance(res, Mapping): + return hookimpl_config_from_mapping(res) + return None + + def _discover_hookimpl_configuration( + self, plugin: _Plugin, name: str + ) -> HookimplConfiguration | None: + """Discover hookimpl configuration for registration. + + Prefer the modern marker attribute. Only call the deprecated + :meth:`parse_hookimpl_opts` when a subclass actually overrides it and + no modern configuration was found (pytest unmarked-hook concession). + """ + config = self._read_hookimpl_configuration(plugin, name) + if config is not None: + return config + parse_hookimpl_opts = type(self).parse_hookimpl_opts + if parse_hookimpl_opts is PluginManager.parse_hookimpl_opts: + return None + legacy = parse_hookimpl_opts(self, plugin, name) + if legacy is None: + return None + return hookimpl_config_from_mapping(legacy) + + def parse_hookimpl_opts(self, plugin: _Plugin, name: str) -> HookimplOpts | None: + """Return legacy dict-shaped hookimpl options, if any. + + .. deprecated:: + Thin pytest/support concession. Registration uses private discovery + of :class:`HookimplConfiguration` and only invokes this method when + a subclass overrides it and no modern configuration attribute was + found. Prefer marker-attached configuration objects. + """ + config = self._read_hookimpl_configuration(plugin, name) + if config is None: + return None + return cast(HookimplOpts, hookimpl_config_to_mapping(config)) def unregister( self, plugin: _Plugin | None = None, name: str | None = None @@ -242,15 +277,15 @@ def add_hookspecs(self, module_or_class: _Namespace) -> None: """ names = [] for name in dir(module_or_class): - spec_opts = self.parse_hookspec_opts(module_or_class, name) - if spec_opts is not None: + spec_config = self._discover_hookspec_configuration(module_or_class, name) + if spec_config is not None: hc: HookCaller | None = getattr(self.hook, name, None) if hc is None: - hc = HookCaller(name, self._hookexec, module_or_class, spec_opts) + hc = HookCaller(name, self._hookexec, module_or_class, spec_config) setattr(self.hook, name, hc) else: # Plugins registered this hook without knowing the spec. - hc.set_specification(module_or_class, spec_opts) + hc.set_specification(module_or_class, spec_config) for hookfunction in hc.get_hookimpls(): self._verify_hook(hc, hookfunction) names.append(name) @@ -260,23 +295,59 @@ def add_hookspecs(self, module_or_class: _Namespace) -> None: f"did not find any {self.project_name!r} hooks in {module_or_class!r}" ) + def _read_hookspec_configuration( + self, module_or_class: _Namespace, name: str + ) -> HookspecConfiguration | None: + """Read a modern :class:`HookspecConfiguration` from a marked function.""" + try: + method = getattr(module_or_class, name) + except Exception: + return None + try: + opts: object = getattr(method, self.project_name + "_spec", None) + except Exception: # pragma: no cover + return None + if isinstance(opts, HookspecConfiguration): + return opts + if isinstance(opts, Mapping): + return hookspec_config_from_mapping(opts) + return None + + def _discover_hookspec_configuration( + self, module_or_class: _Namespace, name: str + ) -> HookspecConfiguration | None: + """Discover hookspec configuration for ``add_hookspecs``. + + Prefer the modern marker attribute. Only call the deprecated + :meth:`parse_hookspec_opts` when a subclass actually overrides it and + no modern configuration was found. + """ + config = self._read_hookspec_configuration(module_or_class, name) + if config is not None: + return config + parse_hookspec_opts = type(self).parse_hookspec_opts + if parse_hookspec_opts is PluginManager.parse_hookspec_opts: + return None + legacy = parse_hookspec_opts(self, module_or_class, name) + if legacy is None: + return None + return hookspec_config_from_mapping(legacy) + def parse_hookspec_opts( self, module_or_class: _Namespace, name: str ) -> HookspecOpts | None: - """Try to obtain a hook specification from an item with the given name - in the given module or class which is being searched for hook specs. - - :returns: - The parsed hookspec options for defining a hook, or None to skip the - given item. + """Return legacy dict-shaped hookspec options, if any. - This method can be overridden by ``PluginManager`` subclasses to - customize how hook specifications are picked up. By default, returns the - options for items decorated with :class:`HookspecMarker`. + .. deprecated:: + Thin pytest/support concession. ``add_hookspecs`` uses private + discovery of :class:`HookspecConfiguration` and only invokes this + method when a subclass overrides it and no modern configuration + attribute was found. Prefer marker-attached configuration objects. """ - method = getattr(module_or_class, name) - opts: HookspecOpts | None = getattr(method, self.project_name + "_spec", None) - return opts + config = self._read_hookspec_configuration(module_or_class, name) + if config is None: + return None + return cast(HookspecOpts, hookspec_config_to_mapping(config)) def get_plugins(self) -> set[Any]: """Return a set of all registered plugin objects.""" diff --git a/src/pluggy/_pytest_compat.py b/src/pluggy/_pytest_compat.py new file mode 100644 index 00000000..9088c0f8 --- /dev/null +++ b/src/pluggy/_pytest_compat.py @@ -0,0 +1,55 @@ +"""Pytest/support compatibility helpers for legacy option encodings. + +The live pluggy API uses :class:`~pluggy.HookspecConfiguration` and +:class:`~pluggy.HookimplConfiguration`. This module keeps TypedDict shapes and +mapping conversion for pytest and other callers that still type or attach +dict-shaped options during migration. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TypedDict + +from ._config import hookimpl_config_from_mapping +from ._config import HookimplConfiguration +from ._config import hookspec_config_from_mapping +from ._config import HookspecConfiguration + + +class HookspecOpts(TypedDict): + """Legacy TypedDict for hook specification options. + + Prefer :class:`~pluggy.HookspecConfiguration`. Kept for pytest/typing + compatibility during migration. + """ + + firstresult: bool + historic: bool + warn_on_impl: Warning | None + warn_on_impl_args: Mapping[str, Warning] | None + + +class HookimplOpts(TypedDict): + """Legacy TypedDict for hook implementation options. + + Prefer :class:`~pluggy.HookimplConfiguration`. Kept for pytest/typing + compatibility during migration. + """ + + wrapper: bool + hookwrapper: bool + optionalhook: bool + tryfirst: bool + trylast: bool + specname: str | None + + +__all__ = [ + "HookspecOpts", + "HookimplOpts", + "HookspecConfiguration", + "HookimplConfiguration", + "hookspec_config_from_mapping", + "hookimpl_config_from_mapping", +] diff --git a/testing/test_configuration.py b/testing/test_configuration.py new file mode 100644 index 00000000..c92ee6f3 --- /dev/null +++ b/testing/test_configuration.py @@ -0,0 +1,276 @@ +""" +Tests for configuration classes. +""" + +from __future__ import annotations + +import pytest + +from pluggy import HookimplConfiguration +from pluggy import HookimplMarker +from pluggy import HookspecConfiguration +from pluggy import HookspecMarker +from pluggy import PluginManager +from pluggy._config import hookimpl_config_from_mapping +from pluggy._config import hookspec_config_from_mapping + + +class TestHookspecConfiguration: + def test_basic_creation(self) -> None: + config = HookspecConfiguration() + assert config.firstresult is False + assert config.historic is False + assert config.warn_on_impl is None + assert config.warn_on_impl_args is None + + def test_firstresult(self) -> None: + config = HookspecConfiguration(firstresult=True) + assert config.firstresult is True + assert config.historic is False + + def test_historic(self) -> None: + config = HookspecConfiguration(historic=True) + assert config.firstresult is False + assert config.historic is True + + def test_historic_firstresult_validation(self) -> None: + with pytest.raises(ValueError, match="cannot have a historic firstresult"): + HookspecConfiguration(historic=True, firstresult=True) + + def test_warn_on_impl(self) -> None: + warning = UserWarning("test warning") + config = HookspecConfiguration(warn_on_impl=warning) + assert config.warn_on_impl is warning + + def test_warn_on_impl_args(self) -> None: + warnings_dict = {"arg1": UserWarning("arg1 warning")} + config = HookspecConfiguration(warn_on_impl_args=warnings_dict) + assert config.warn_on_impl_args is warnings_dict + + +class TestHookimplConfiguration: + def test_basic_creation(self) -> None: + config = HookimplConfiguration() + assert config.wrapper is False + assert config.hookwrapper is False + assert config.optionalhook is False + assert config.tryfirst is False + assert config.trylast is False + assert config.specname is None + + def test_wrapper(self) -> None: + config = HookimplConfiguration(wrapper=True) + assert config.wrapper is True + assert config.hookwrapper is False + + def test_hookwrapper(self) -> None: + config = HookimplConfiguration(hookwrapper=True) + assert config.wrapper is False + assert config.hookwrapper is True + + def test_both_wrappers_allowed(self) -> None: + """Both wrapper types are allowed at config level; validation is later.""" + config = HookimplConfiguration(wrapper=True, hookwrapper=True) + assert config.wrapper is True + assert config.hookwrapper is True + + def test_tryfirst(self) -> None: + config = HookimplConfiguration(tryfirst=True) + assert config.tryfirst is True + assert config.trylast is False + + def test_trylast(self) -> None: + config = HookimplConfiguration(trylast=True) + assert config.tryfirst is False + assert config.trylast is True + + def test_optionalhook(self) -> None: + config = HookimplConfiguration(optionalhook=True) + assert config.optionalhook is True + + def test_specname(self) -> None: + config = HookimplConfiguration(specname="custom_name") + assert config.specname == "custom_name" + + +class TestMappingShim: + def test_hookspec_config_from_mapping(self) -> None: + warning = UserWarning("w") + config = hookspec_config_from_mapping( + { + "firstresult": True, + "warn_on_impl": warning, + } + ) + assert config.firstresult is True + assert config.historic is False + assert config.warn_on_impl is warning + + def test_hookimpl_config_from_mapping(self) -> None: + config = hookimpl_config_from_mapping( + { + "tryfirst": True, + "specname": "other", + } + ) + assert config.tryfirst is True + assert config.specname == "other" + assert config.wrapper is False + + def test_read_hookimpl_accepts_legacy_dict_attribute(self) -> None: + pm = PluginManager("test") + + def method() -> str: + return "ok" + + setattr(method, "test_impl", {"tryfirst": True}) + + class Plugin: + pass + + plugin = Plugin() + plugin.method = method # type: ignore[attr-defined] + config = pm._read_hookimpl_configuration(plugin, "method") + assert isinstance(config, HookimplConfiguration) + assert config.tryfirst is True + + def test_parse_hookimpl_opts_returns_legacy_dict(self) -> None: + hookimpl = HookimplMarker("test") + + @hookimpl(tryfirst=True) + def method() -> str: + return "ok" + + class Plugin: + pass + + plugin = Plugin() + plugin.method = method # type: ignore[attr-defined] + opts = PluginManager("test").parse_hookimpl_opts(plugin, "method") + assert opts == { + "wrapper": False, + "hookwrapper": False, + "optionalhook": False, + "tryfirst": True, + "trylast": False, + "specname": None, + } + + def test_read_hookspec_accepts_legacy_dict_attribute(self) -> None: + pm = PluginManager("test") + + class Spec: + def myhook(self) -> None: + pass + + setattr(Spec.myhook, "test_spec", {"firstresult": True}) + config = pm._read_hookspec_configuration(Spec, "myhook") + assert isinstance(config, HookspecConfiguration) + assert config.firstresult is True + + def test_discover_skips_parse_hookimpl_opts_unless_overridden(self) -> None: + calls: list[str] = [] + + class TrackingPluginManager(PluginManager): + def parse_hookimpl_opts(self, plugin: object, name: str): + calls.append(name) + return super().parse_hookimpl_opts(plugin, name) + + class Spec: + @HookspecMarker("test") + def marked(self) -> None: + pass + + def unmarked(self) -> None: + pass + + class Plugin: + @HookimplMarker("test") + def marked(self) -> str: + return "marked" + + def unmarked(self) -> str: + return "unmarked" + + pm = TrackingPluginManager("test") + pm.add_hookspecs(Spec) + pm.register(Plugin()) + # Marked impl is discovered privately; unmarked has no config and the + # override returns None, so parse_hookimpl_opts is only tried for names + # without a modern configuration attribute. + assert "marked" not in calls + assert "unmarked" in calls + + +def test_markers_attach_configuration_objects() -> None: + hookspec = HookspecMarker("test") + hookimpl = HookimplMarker("test") + + @hookspec(firstresult=True) + def myspec(arg: object) -> None: + pass + + @hookimpl(tryfirst=True) + def myimpl(arg: object) -> str: + return "x" + + spec_config = getattr(myspec, "test_spec") + impl_config = getattr(myimpl, "test_impl") + assert isinstance(spec_config, HookspecConfiguration) + assert spec_config.firstresult is True + assert isinstance(impl_config, HookimplConfiguration) + assert impl_config.tryfirst is True + + +def test_config_integration_with_hooks() -> None: + pm = PluginManager("test") + hookspec = HookspecMarker("test") + hookimpl = HookimplMarker("test") + + class MySpec: + @hookspec(firstresult=True) + def myhook(self, arg: object) -> None: + pass + + class Plugin1: + @hookimpl(trylast=True) + def myhook(self, arg: object) -> str: + return f"plugin1: {arg}" + + class Plugin2: + @hookimpl(tryfirst=True) + def myhook(self, arg: object) -> str: + return f"plugin2: {arg}" + + pm.add_hookspecs(MySpec) + pm.register(Plugin1()) + pm.register(Plugin2()) + + result = pm.hook.myhook(arg="test") + assert result == "plugin2: test" + + +def test_historic_hook_configuration() -> None: + pm = PluginManager("test") + hookspec = HookspecMarker("test") + hookimpl = HookimplMarker("test") + + results: list[str] = [] + + class MySpec: + @hookspec(historic=True) + def myhook(self, arg: object) -> None: + pass + + pm.add_hookspecs(MySpec) + pm.hook.myhook.call_historic( + kwargs={"arg": "call1"}, result_callback=results.append + ) + + class Plugin1: + @hookimpl + def myhook(self, arg: object) -> str: + return f"plugin1: {arg}" + + pm.register(Plugin1()) + assert "plugin1: call1" in results diff --git a/testing/test_details.py b/testing/test_details.py index 237b7de1..838a7d35 100644 --- a/testing/test_details.py +++ b/testing/test_details.py @@ -16,10 +16,11 @@ def test_parse_hookimpl_override() -> None: class MyPluginManager(PluginManager): def parse_hookimpl_opts(self, module_or_class, name): opts = PluginManager.parse_hookimpl_opts(self, module_or_class, name) - if opts is None: - if name.startswith("x1"): - opts = {} # type: ignore[assignment] - return opts + if opts is not None: + return opts + if name.startswith("x1"): + return {} + return None class Plugin: def x1meth(self): diff --git a/testing/test_hookcaller.py b/testing/test_hookcaller.py index 0c9f91bd..17e3d812 100644 --- a/testing/test_hookcaller.py +++ b/testing/test_hookcaller.py @@ -317,11 +317,11 @@ def he_myhook3(self, arg1) -> None: pm.add_hookspecs(HookSpec) assert pm.hook.he_myhook1.spec is not None - assert not pm.hook.he_myhook1.spec.opts["firstresult"] + assert not pm.hook.he_myhook1.spec.opts.firstresult assert pm.hook.he_myhook2.spec is not None - assert pm.hook.he_myhook2.spec.opts["firstresult"] + assert pm.hook.he_myhook2.spec.opts.firstresult assert pm.hook.he_myhook3.spec is not None - assert not pm.hook.he_myhook3.spec.opts["firstresult"] + assert not pm.hook.he_myhook3.spec.opts.firstresult @pytest.mark.parametrize("name", ["hookwrapper", "optionalhook", "tryfirst", "trylast"]) @@ -332,7 +332,7 @@ def he_myhook1(arg1) -> None: pass if val: - assert he_myhook1.example_impl.get(name) + assert getattr(he_myhook1.example_impl, name) else: assert not hasattr(he_myhook1, name)