Skip to content
Draft
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions stdlib/operator.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,16 @@ from _operator import (
xor as xor,
)
from _typeshed import SupportsGetItem
from typing import Any, Generic, TypeVar, final, overload
from typing import Any, Generic, ParamSpec, TypeVar, final, overload
from typing_extensions import Self, TypeVarTuple, Unpack

_T = TypeVar("_T")
_T_co = TypeVar("_T_co", covariant=True)
_T1 = TypeVar("_T1")
_T2 = TypeVar("_T2")
_Ts = TypeVarTuple("_Ts")
_P = ParamSpec("_P", default=...)
_R = TypeVar("_R", default=Any)

__all__ = [
"abs",
Expand Down Expand Up @@ -182,6 +184,8 @@ if sys.version_info >= (3, 11):
# them here.
@final
class attrgetter(Generic[_T_co]):
# We can't determine the type of the attribute(s) being accessed statucally,
# so we have to use Any for the return type.
@overload
def __new__(cls, attr: str, /) -> attrgetter[Any]: ...
@overload
Expand All @@ -192,6 +196,8 @@ class attrgetter(Generic[_T_co]):
def __new__(cls, attr: str, attr2: str, attr3: str, attr4: str, /) -> attrgetter[tuple[Any, Any, Any, Any]]: ...
@overload
def __new__(cls, attr: str, /, *attrs: str) -> attrgetter[tuple[Any, ...]]: ...
# obj needs to have the named attribute(s) with the correct type.
# Unfortunately, we can't check that statically, so we need to use Any.
def __call__(self, obj: Any, /) -> _T_co: ...

@final
Expand All @@ -212,6 +218,8 @@ class itemgetter(Generic[_T_co]):
def __call__(self, obj: SupportsGetItem[Any, Any]) -> Any: ...

@final
class methodcaller:
def __new__(cls, name: str, /, *args: Any, **kwargs: Any) -> Self: ...
def __call__(self, obj: Any) -> Any: ...
class methodcaller(Generic[_P, _R]):
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Making this generic, makes it possible to use better methodcallers in annotations, even if type checking is not perfect:

m: methodcaller[[int], str] = methodcaller("foo")  # error (missing argument)

I'll add some tests.

def __new__(cls, name: str, /, *args: _P.args, **kwargs: _P.kwargs) -> Self: ...
# obj needs to have the named method with the correct signature.
# Unfortunately, we can't check that statically, so we need to use Any.
def __call__(self, obj: Any) -> _R: ...