[issue4331] Add functools.partialmethod
alon horev
report at bugs.python.org
Sat Oct 26 16:59:36 CEST 2013
alon horev added the comment:
Here's another attempt at a consistent api with regular methods.
I'm contemplating whether partialmethod should support __call__. Given the fact partial is used to bind positional arguments, it will do the 'wrong' thing when calling the partialmethod directly and will shift all positional arguments (example at the last line of the snippet).
I also think staticmethod in this context is useless but agree consistency is a thing (you could just use partial instead).
If consistency hadn't held us back, the first proposal of partialmethod, working both for instances and classes, would have been most elegant.
from functools import partial
class partialmethod(object):
def __init__(self, func, *args, **keywords):
self.func = func
self.args = args
self.keywords = keywords
def __call__(self, *args, **keywords):
call_keywords = {}
call_keywords.update(self.keywords)
call_keywords.update(keywords)
return self.func(*(self.args + args), **call_keywords)
def __get__(self, obj, cls):
return partial(self.func.__get__(obj, cls), *self.args, **self.keywords)
class A(object):
def add(self, x, y):
print(self)
return x + y
add10 = partialmethod(add, 10)
add10class = partialmethod(classmethod(add), 10)
add10static = partialmethod(staticmethod(add), 'self', 10)
assert A().add10(5) == 15 # prints <__main__.A object at 0x1097e1390>
assert A.add10class(5) == 15 # prints <class '__main__.A'>
assert A.add10static(5) == 15 # prints self
assert A.add10(2, 3) == 5 # prints 10 because the first positional argument is self..
Once we approve of the API I'll provide a full fledged patch.
----------
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue4331>
_______________________________________
More information about the Python-bugs-list
mailing list