Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork32k
gh-124652: partialmethod simplifications#124788
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Open
dg-pb wants to merge18 commits intopython:mainChoose a base branch fromdg-pb:gh-124652-partialmethod
base:main
Could not load branches
Branch not found:{{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline, and old review comments may become outdated.
+133 −127
Open
Changes fromall commits
Commits
Show all changes
18 commits Select commitHold shift + click to select a range
9262323
fix
dg-pb3c4edd8
test fixes
dg-pb2a843bc
merge
dg-pbf43b69e
minor edits
dg-pb90dc0fd
trailing placeholder restriction removed
dg-pb10ee972
rm commented code
dg-pbb76ffee
put back accidental removal
dg-pb8fa0ec5
test_trailing_placeholders and bug fix
dg-pbf323dbd
full backwards compatibility
dg-pbd217592
small edits
dg-pb88422c4
📜🤖 Added by blurb_it.
blurb-it[bot]79e9cff
Merge remote-tracking branch 'upstream/main' into gh-124652-partialme…
dg-pb27493b3
restore previous _unwrap_partial
dg-pb7b24727
is tuple rollback
dg-pb4f33459
leading trailing placeholder lift factored out
dg-pbc3df6e0
remove extra blank line
dg-pbfca3d7d
rollback unnecessary changes
dg-pbec64137
Merge remote-tracking branch 'upstream/main' into gh-124652-partialme…
dg-pbFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -14,12 +14,12 @@ | ||
'partial', 'partialmethod', 'singledispatch', 'singledispatchmethod', | ||
'cached_property', 'Placeholder'] | ||
from abc importabstractmethod,get_cache_token | ||
from collections import namedtuple | ||
# import weakref # Deferred to single_dispatch() | ||
from operator import itemgetter | ||
from reprlib import recursive_repr | ||
from types importFunctionType,GenericAlias, MethodType, MappingProxyType, UnionType | ||
from _thread import RLock | ||
################################################################################ | ||
@@ -310,52 +310,6 @@ def _partial_prepare_merger(args): | ||
merger = itemgetter(*order) if phcount else None | ||
return phcount, merger | ||
def _partial_repr(self): | ||
cls = type(self) | ||
module = cls.__module__ | ||
@@ -374,7 +328,44 @@ class partial: | ||
__slots__ = ("func", "args", "keywords", "_phcount", "_merger", | ||
"__dict__", "__weakref__") | ||
def __new__(cls, func, /, *args, **keywords): | ||
if not callable(func): | ||
raise TypeError("the first argument must be callable") | ||
if args and args[-1] is Placeholder: | ||
raise TypeError("trailing Placeholders are not allowed") | ||
for value in keywords.values(): | ||
if value is Placeholder: | ||
raise TypeError("Placeholder cannot be passed as a keyword argument") | ||
if isinstance(func, partial): | ||
pto_phcount = func._phcount | ||
tot_args = func.args | ||
if args: | ||
tot_args += args | ||
if pto_phcount: | ||
# merge args with args of `func` which is `partial` | ||
nargs = len(args) | ||
if nargs < pto_phcount: | ||
tot_args += (Placeholder,) * (pto_phcount - nargs) | ||
tot_args = func._merger(tot_args) | ||
if nargs > pto_phcount: | ||
tot_args += args[pto_phcount:] | ||
phcount, merger = _partial_prepare_merger(tot_args) | ||
else: # works for both pto_phcount == 0 and != 0 | ||
phcount, merger = pto_phcount, func._merger | ||
keywords = {**func.keywords, **keywords} | ||
func = func.func | ||
else: | ||
tot_args = args | ||
phcount, merger = _partial_prepare_merger(tot_args) | ||
self = object.__new__(cls) | ||
self.func = func | ||
self.args = tot_args | ||
self.keywords = keywords | ||
self._phcount = phcount | ||
self._merger = merger | ||
return self | ||
__repr__ = recursive_repr()(_partial_repr) | ||
def __call__(self, /, *args, **keywords): | ||
@@ -439,6 +430,10 @@ def __setstate__(self, state): | ||
except ImportError: | ||
pass | ||
_NULL = object() | ||
_UNKNOWN_DESCRIPTOR = object() | ||
_STD_METHOD_TYPES = (staticmethod, classmethod, FunctionType, partial) | ||
# Descriptor version | ||
class partialmethod: | ||
"""Method descriptor with partial application of the given arguments | ||
@@ -447,54 +442,94 @@ class partialmethod: | ||
Supports wrapping existing descriptors and handles non-descriptor | ||
callables as instance methods. | ||
""" | ||
__slots__ = ("func", "args", "keywords", "wrapper", | ||
dg-pb marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
"__dict__", "__weakref__") | ||
__repr__ = _partial_repr | ||
def __init__(self, func, /, *args, **keywords): | ||
if isinstance(func, partialmethod): | ||
# Subclass optimization | ||
temp = partial(lambda: None, *func.args, **func.keywords) | ||
temp = partial(temp, *args, **keywords) | ||
func = func.func | ||
args = temp.args | ||
keywords = temp.keywords | ||
self.func = func | ||
self.args = args | ||
self.keywords = keywords | ||
if isinstance(func, _STD_METHOD_TYPES): | ||
self.method = None | ||
elif getattr(func, '__get__', None) is None: | ||
if not callable(func): | ||
raise TypeError(f'the first argument {func!r} must be a callable ' | ||
'or a descriptor') | ||
self.method = None | ||
else: | ||
# Unknown descriptor | ||
self.method = _UNKNOWN_DESCRIPTOR | ||
def _set_func_attrs(self, func): | ||
func.__partialmethod__ = self | ||
if self.__isabstractmethod__: | ||
func = abstractmethod(func) | ||
return func | ||
def _make_method(self): | ||
args = self.args | ||
func = self.func | ||
# 4 cases | ||
if isinstance(func, staticmethod): | ||
deco = staticmethod | ||
method = partial(func.__wrapped__, *args, **self.keywords) | ||
elif isinstance(func, classmethod): | ||
deco = classmethod | ||
ph_args = (Placeholder,) if args else () | ||
method = partial(func.__wrapped__, *ph_args, *args, **self.keywords) | ||
else: | ||
# instance method. 2 cases: | ||
# a) FunctionType | partial | ||
# b) callable object without __get__ | ||
deco = None | ||
ph_args = (Placeholder,) if args else () | ||
method = partial(func, *ph_args, *args, **self.keywords) | ||
method.__partialmethod__ = self | ||
if self.__isabstractmethod__: | ||
method = abstractmethod(method) | ||
if deco is not None: | ||
method = deco(method) | ||
return method | ||
def __get__(self, obj, cls=None): | ||
method = self.method | ||
if method is _UNKNOWN_DESCRIPTOR: | ||
# Unknown descriptor == unknown binding | ||
# Need toget callable at runtime and apply partial on top | ||
new_func=self.func.__get__(obj, cls) | ||
result = partial(new_func, *self.args, **self.keywords) | ||
result.__partialmethod__ = self | ||
ifself.__isabstractmethod__: | ||
result = abstractmethod(result) | ||
__self__ =getattr(new_func, '__self__', _NULL) | ||
if __self__ is not _NULL: | ||
result.__self__ = __self__ | ||
return result | ||
if method is None: | ||
#Cache method | ||
self.method =method =self._make_method() | ||
returnmethod.__get__(obj, cls) | ||
@property | ||
def __isabstractmethod__(self): | ||
return getattr(self.func, "__isabstractmethod__", False) | ||
__class_getitem__ = classmethod(GenericAlias) | ||
# Helper functions | ||
def _unwrap_partial(func): | ||
@@ -506,13 +541,14 @@ def _unwrap_partialmethod(func): | ||
prev = None | ||
while func is not prev: | ||
prev = func | ||
__partialmethod__ =getattr(func, "__partialmethod__", None) | ||
if isinstance(__partialmethod__, partialmethod): | ||
func = __partialmethod__.func | ||
if isinstance(func, (partial, partialmethod)): | ||
func = func.func | ||
return func | ||
################################################################################ | ||
### LRU Cache function decorator | ||
################################################################################ | ||
33 changes: 0 additions & 33 deletionsLib/inspect.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
8 changes: 5 additions & 3 deletionsLib/test/test_inspect/test_inspect.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
1 change: 1 addition & 0 deletionsMisc/NEWS.d/next/Library/2024-10-17-00-50-32.gh-issue-124652.AK3PDp.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
:func:`functools.partialmethod` is simplified by making use of new :func:`functools.partial` placeholder functionality. |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.