python: export method as function close over object
Question: In python I would like to export an object-method as a normal function. The
object will be closed over. Like in the following:

    
    
    from functools import partial
    
    class A(object):
        def __init__(self,a):
            self.a = a
    
        def m(self,b):
            return self.a+b
    
        def exportm(self):
            return lambda b,self=self: self.m(b)
            #return partial(self.m,self=self)
    
    f = A(10).exportm()
    
    print f(5)
    

This works well and prints 15 as expected. But if I replace the return-lambda-
line with the commented line it will fail giving the following error:

    
    
    TypeError: m() got multiple values for keyword argument 'self'
    

I understand that using functools is cleaner than resorting to lambda
expressions. So I'd like to know how to do this using partial or some other
tool in functools.


Answer: `self.m` is already bound, so there's no need to pass `self=self` to it.
Simply return `self.m`. For more arguments, use `partial(self.m, ...)`:

    
    
    class A(object):
        def __init__(self, a):
            self.a = a
    
        def m(self, b, c):
            return self.a + b + c
    
        def exportm(self):
            return partial(self.m, 300)
    
    f = A(10).exportm()
    print f(5)
    

