func_tools: Add module
Add the func_tools module for giving the private_method decorator a home. The decorator enforces that a method can only be called by methods belonging to the same class. It inspects the call stack at runtime and raises AttributeError if the caller is not a method of the owning class. When decorating a class, the decorator scans all other class members for functions (including static, class, and other private methods) and records their code objects as allowed callers. The __get__() method returns a wrapper that checks the current frame's code object against this set before dispatching to the actual method. Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
parent
5a8dfab722
commit
0d3008d656
1 changed files with 79 additions and 0 deletions
79
src/python/jw/util/func_tools.py
Normal file
79
src/python/jw/util/func_tools.py
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
|
||||
from functools import wraps
|
||||
from types import CodeType, FunctionType
|
||||
from typing import (TYPE_CHECKING, Concatenate, Generic, ParamSpec, TypeVar, overload)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
_T = TypeVar("_T")
|
||||
_P = ParamSpec("_P")
|
||||
_R = TypeVar("_R")
|
||||
|
||||
class private_method(Generic[_T, _P, _R]):
|
||||
|
||||
def __init__(self, func: Callable[Concatenate[_T, _P], _R]) -> None:
|
||||
self.func = func
|
||||
self.owner: type[_T] | None = None
|
||||
self.allowed_callers: set[CodeType] = set()
|
||||
|
||||
name = getattr(func, "__name__", None)
|
||||
self.name = name if isinstance(name, str) else "<private method>"
|
||||
|
||||
def __set_name__(self, owner: type[_T], name: str) -> None:
|
||||
self.owner = owner
|
||||
|
||||
for raw_value in owner.__dict__.values():
|
||||
value = raw_value
|
||||
|
||||
if isinstance(value, staticmethod):
|
||||
value = value.__func__
|
||||
elif isinstance(value, classmethod):
|
||||
value = value.__func__
|
||||
elif isinstance(value, private_method):
|
||||
value = value.func
|
||||
|
||||
if isinstance(value, FunctionType):
|
||||
self.allowed_callers.add(value.__code__)
|
||||
|
||||
@overload
|
||||
def __get__(self,
|
||||
obj: None,
|
||||
objtype: type[_T] | None = None) -> private_method[_T, _P, _R]:
|
||||
...
|
||||
|
||||
@overload
|
||||
def __get__(self, obj: _T, objtype: type[_T] | None = None) -> Callable[_P, _R]:
|
||||
...
|
||||
|
||||
def __get__(
|
||||
self,
|
||||
obj: _T | None,
|
||||
objtype: type[_T] | None = None,
|
||||
) -> private_method[_T, _P, _R] | Callable[_P, _R]:
|
||||
if obj is None:
|
||||
return self
|
||||
|
||||
@wraps(self.func)
|
||||
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
||||
current_frame = inspect.currentframe()
|
||||
caller_frame = current_frame.f_back if current_frame is not None else None
|
||||
try:
|
||||
if (caller_frame is None
|
||||
or caller_frame.f_code not in self.allowed_callers):
|
||||
owner_name = (
|
||||
self.owner.__qualname__
|
||||
if self.owner is not None else "<unknown>"
|
||||
)
|
||||
|
||||
raise AttributeError(f"{owner_name}.{self.name} is private")
|
||||
|
||||
return self.func(obj, *args, **kwargs)
|
||||
finally:
|
||||
del caller_frame
|
||||
del current_frame
|
||||
|
||||
return wrapper
|
||||
Loading…
Reference in a new issue