Author alonho
Recipients Alexander.Belopolsky, Christophe Simonis, alonho, anacrolix, belopolsky, eckhardt, ironfroggy, jackdied, jcea, ncoghlan, r.david.murray, rhettinger, ssadler
Date 2013-10-26.14:59:35
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1382799576.01.0.647568450466.issue4331@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2013-10-26 14:59:36alonhosetrecipients: + alonho, rhettinger, jcea, ncoghlan, belopolsky, ironfroggy, jackdied, Christophe Simonis, ssadler, eckhardt, r.david.murray, Alexander.Belopolsky, anacrolix
2013-10-26 14:59:36alonhosetmessageid: <1382799576.01.0.647568450466.issue4331@psf.upfronthosting.co.za>
2013-10-26 14:59:35alonholinkissue4331 messages
2013-10-26 14:59:35alonhocreate