Skip to content

Commit

Permalink
Merge pull request #390 from bluetech/future-annotations
Browse files Browse the repository at this point in the history
Use `from __future__ import annotations`
  • Loading branch information
bluetech committed Jun 12, 2023
2 parents 250081a + 0673c99 commit c13a6b7
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 101 deletions.
12 changes: 6 additions & 6 deletions src/pluggy/_callers.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""
Call loop machinery
"""
from __future__ import annotations

from typing import cast
from typing import Generator
from typing import List
from typing import Mapping
from typing import Sequence
from typing import TYPE_CHECKING
from typing import Union

from ._result import _raise_wrapfail
from ._result import _Result
Expand All @@ -19,17 +19,17 @@

def _multicall(
hook_name: str,
hook_impls: Sequence["HookImpl"],
hook_impls: Sequence[HookImpl],
caller_kwargs: Mapping[str, object],
firstresult: bool,
) -> Union[object, List[object]]:
) -> 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] = []
results: list[object] = []
exception = None
try: # run impl and wrapper setup functions in a loop
teardowns = []
Expand Down Expand Up @@ -64,7 +64,7 @@ def _multicall(
exception = exc
finally:
if firstresult: # first result hooks return a single value
outcome: _Result[Union[object, List[object]]] = _Result(
outcome: _Result[object | list[object]] = _Result(
results[0] if results else None, exception
)
else:
Expand Down
82 changes: 42 additions & 40 deletions src/pluggy/_hooks.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""
Internal hook annotation, representation and calling machinery.
"""
from __future__ import annotations

import inspect
import sys
import warnings
Expand Down Expand Up @@ -40,14 +42,14 @@
class _HookSpecOpts(TypedDict):
firstresult: bool
historic: bool
warn_on_impl: Optional[Warning]
warn_on_impl: Warning | None

class _HookImplOpts(TypedDict):
hookwrapper: bool
optionalhook: bool
tryfirst: bool
trylast: bool
specname: Optional[str]
specname: str | None


class HookspecMarker:
Expand All @@ -61,15 +63,15 @@ class HookspecMarker:
__slots__ = ("project_name",)

def __init__(self, project_name: str) -> None:
self.project_name: "Final" = project_name
self.project_name: Final = project_name

@overload
def __call__(
self,
function: _F,
firstresult: bool = False,
historic: bool = False,
warn_on_impl: Optional[Warning] = None,
warn_on_impl: Warning | None = None,
) -> _F:
...

Expand All @@ -79,17 +81,17 @@ def __call__( # noqa: F811
function: None = ...,
firstresult: bool = ...,
historic: bool = ...,
warn_on_impl: Optional[Warning] = ...,
warn_on_impl: Warning | None = ...,
) -> Callable[[_F], _F]:
...

def __call__( # noqa: F811
self,
function: Optional[_F] = None,
function: _F | None = None,
firstresult: bool = False,
historic: bool = False,
warn_on_impl: Optional[Warning] = None,
) -> Union[_F, Callable[[_F], _F]]:
warn_on_impl: 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`.
Expand All @@ -107,7 +109,7 @@ 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" = {
opts: _HookSpecOpts = {
"firstresult": firstresult,
"historic": historic,
"warn_on_impl": warn_on_impl,
Expand All @@ -132,7 +134,7 @@ class HookimplMarker:
__slots__ = ("project_name",)

def __init__(self, project_name: str) -> None:
self.project_name: "Final" = project_name
self.project_name: Final = project_name

@overload
def __call__(
Expand All @@ -142,7 +144,7 @@ def __call__(
optionalhook: bool = ...,
tryfirst: bool = ...,
trylast: bool = ...,
specname: Optional[str] = ...,
specname: str | None = ...,
) -> _F:
...

Expand All @@ -154,19 +156,19 @@ def __call__( # noqa: F811
optionalhook: bool = ...,
tryfirst: bool = ...,
trylast: bool = ...,
specname: Optional[str] = ...,
specname: str | None = ...,
) -> Callable[[_F], _F]:
...

def __call__( # noqa: F811
self,
function: Optional[_F] = None,
function: _F | None = None,
hookwrapper: bool = False,
optionalhook: bool = False,
tryfirst: bool = False,
trylast: bool = False,
specname: Optional[str] = None,
) -> Union[_F, Callable[[_F], _F]]:
specname: str | None = None,
) -> _F | Callable[[_F], _F]:
"""If passed a function, directly sets attributes on the function
which will make it discoverable to :meth:`PluginManager.register`.
Expand Down Expand Up @@ -197,7 +199,7 @@ def __call__( # noqa: F811
"""

def setattr_hookimpl_opts(func: _F) -> _F:
opts: "_HookImplOpts" = {
opts: _HookImplOpts = {
"hookwrapper": hookwrapper,
"optionalhook": optionalhook,
"tryfirst": tryfirst,
Expand All @@ -213,7 +215,7 @@ def setattr_hookimpl_opts(func: _F) -> _F:
return setattr_hookimpl_opts(function)


def normalize_hookimpl_opts(opts: "_HookImplOpts") -> None:
def normalize_hookimpl_opts(opts: _HookImplOpts) -> None:
opts.setdefault("tryfirst", False)
opts.setdefault("trylast", False)
opts.setdefault("hookwrapper", False)
Expand All @@ -224,7 +226,7 @@ def normalize_hookimpl_opts(opts: "_HookImplOpts") -> None:
_PYPY = hasattr(sys, "pypy_version_info")


def varnames(func: object) -> Tuple[Tuple[str, ...], Tuple[str, ...]]:
def varnames(func: object) -> tuple[tuple[str, ...], tuple[str, ...]]:
"""Return tuple of positional and keywrord argument names for a function,
method, class or callable.
Expand Down Expand Up @@ -278,7 +280,7 @@ def varnames(func: object) -> Tuple[Tuple[str, ...], Tuple[str, ...]]:
# strip any implicit instance arg
# pypy3 uses "obj" instead of "self" for default dunder methods
if not _PYPY:
implicit_names: Tuple[str, ...] = ("self",)
implicit_names: tuple[str, ...] = ("self",)
else:
implicit_names = ("self", "obj")
if args:
Expand All @@ -297,7 +299,7 @@ class _HookRelay:

if TYPE_CHECKING:

def __getattr__(self, name: str) -> "_HookCaller":
def __getattr__(self, name: str) -> _HookCaller:
...


Expand All @@ -317,14 +319,14 @@ def __init__(
self,
name: str,
hook_execute: _HookExec,
specmodule_or_class: Optional[_Namespace] = None,
spec_opts: Optional["_HookSpecOpts"] = None,
specmodule_or_class: _Namespace | None = None,
spec_opts: _HookSpecOpts | None = None,
) -> None:
self.name: "Final" = name
self._hookexec: "Final" = hook_execute
self._hookimpls: "Final[List[HookImpl]]" = []
self._call_history: Optional[_CallHistory] = None
self.spec: Optional[HookSpec] = None
self.name: Final = name
self._hookexec: Final = hook_execute
self._hookimpls: Final[list[HookImpl]] = []
self._call_history: _CallHistory | None = None
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)
Expand All @@ -335,7 +337,7 @@ def has_spec(self) -> bool:
def set_specification(
self,
specmodule_or_class: _Namespace,
spec_opts: "_HookSpecOpts",
spec_opts: _HookSpecOpts,
) -> None:
assert not self.has_spec()
self.spec = HookSpec(specmodule_or_class, self.name, spec_opts)
Expand All @@ -352,10 +354,10 @@ def _remove_plugin(self, plugin: _Plugin) -> None:
return
raise ValueError(f"plugin {plugin!r} not found")

def get_hookimpls(self) -> List["HookImpl"]:
def get_hookimpls(self) -> list[HookImpl]:
return self._hookimpls.copy()

def _add_hookimpl(self, hookimpl: "HookImpl") -> None:
def _add_hookimpl(self, hookimpl: HookImpl) -> None:
"""Add an implementation to the callback chain."""
for i, method in enumerate(self._hookimpls):
if method.hookwrapper:
Expand Down Expand Up @@ -410,8 +412,8 @@ def __call__(self, **kwargs: object) -> Any:

def call_historic(
self,
result_callback: Optional[Callable[[Any], None]] = None,
kwargs: Optional[Mapping[str, object]] = None,
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.
Expand Down Expand Up @@ -441,7 +443,7 @@ def call_extra(
not self.is_historic()
), "Cannot directly call a historic hook - use call_historic instead."
self._verify_all_args_are_provided(kwargs)
opts: "_HookImplOpts" = {
opts: _HookImplOpts = {
"hookwrapper": False,
"optionalhook": False,
"trylast": False,
Expand All @@ -459,7 +461,7 @@ def call_extra(
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:
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
Expand Down Expand Up @@ -499,19 +501,19 @@ def __init__(self, orig: _HookCaller, remove_plugins: AbstractSet[_Plugin]) -> N
self._hookexec = orig._hookexec # type: ignore[misc]

@property # type: ignore[misc]
def _hookimpls(self) -> List["HookImpl"]:
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) -> Optional["HookSpec"]: # type: ignore[override]
def spec(self) -> HookSpec | None: # type: ignore[override]
return self._orig.spec

@property
def _call_history(self) -> Optional[_CallHistory]: # type: ignore[override]
def _call_history(self) -> _CallHistory | None: # type: ignore[override]
return self._orig._call_history

def __repr__(self) -> str:
Expand All @@ -537,9 +539,9 @@ def __init__(
plugin: _Plugin,
plugin_name: str,
function: _HookImplFunction[object],
hook_impl_opts: "_HookImplOpts",
hook_impl_opts: _HookImplOpts,
) -> None:
self.function: "Final" = function
self.function: Final = function
self.argnames, self.kwargnames = varnames(self.function)
self.plugin = plugin
self.opts = hook_impl_opts
Expand All @@ -564,7 +566,7 @@ class HookSpec:
"warn_on_impl",
)

def __init__(self, namespace: _Namespace, name: str, opts: "_HookSpecOpts") -> None:
def __init__(self, namespace: _Namespace, name: str, opts: _HookSpecOpts) -> None:
self.namespace = namespace
self.function: Callable[..., object] = getattr(namespace, name)
self.name = name
Expand Down

0 comments on commit c13a6b7

Please sign in to comment.