Skip to content

Make weakref.finalize generic per todo comment #8438

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
wants to merge 10 commits into from
2 changes: 1 addition & 1 deletion stdlib/weakref.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]):
@overload
def __ior__(self: Self, other: Iterable[tuple[_KT, _VT]]) -> Self: ...

class finalize: # TODO: This is a good candidate for to be a `Generic[_P, _T]` class
class finalize:
def __init__(self, __obj: object, __func: Callable[_P, Any], *args: _P.args, **kwargs: _P.kwargs) -> None: ...
def __call__(self, _: Any = ...) -> Any | None: ...
def detach(self) -> tuple[Any, Any, tuple[Any, ...], dict[str, Any]] | None: ...
Expand Down
21 changes: 21 additions & 0 deletions test_cases/stdlib/test_weakref.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from typing import Any, Callable, Dict, Optional, Tuple
from typing_extensions import TypeAlias, assert_type
from weakref import finalize

_ResultStructure: TypeAlias = Optional[Tuple[str, Callable[[int, int], int], Tuple[Any, ...], Dict[str, Any]]]


class TObj:
"""_T type var in stubs"""

pass


def callback(x: int, y: int) -> int:
return x + y


final = finalize(TObj, callback, 1, y=2)
assert_type(final.peek(), _ResultStructure)
assert_type(final.detach(), _ResultStructure)
assert_type(final(), int | None)