jw-python/src/python/jw/util/func_tools.py
Jan Lindemann 2d847b4ccd
jw.util, jwutils: Follow jw-pkg's move to isort
"make format", as defined by jw-pkg, now sorts the order or imports,
too. So do that and commit.

Signed-off-by: Jan Lindemann <jan@janware.com>
2026-08-12 23:10:13 +00:00

79 lines
2.4 KiB
Python

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