lang2
lang2

Reputation: 11966

types.MethodType vs functools.partial

This is a continuation of my other question (python closure + oop). In the answer to that question, Winston Ewert suggested me to use functools.partial instead of types.MethodType.

So now my question is: what's the difference between the two? Why is the functool way considered better?

ps. I've managed to use functools.partial for my closure and it did feel cool. :-)

Upvotes: 2

Views: 1140

Answers (1)

SingleNegationElimination
SingleNegationElimination

Reputation: 156158

From a practical stand point, there isn't a whole lot of difference. Partial will curry any number of arguments (in this case, 1); an instancemethod will pass the self instance (whatever that happens to be) to the wrapped function; They're doing the same thing!

The difference is that they somewhat document themselves; In your linked question; the closure callable isn't a method of anything; it's a regular function, returned by a method of A; It happens that the body sees an instance of B as the first argument; but that's not enough to make it a "method" of B.

So it's just a matter of style. You're doing something that looks more like functools.partial, and so you should use that, even though you can achieve the same effect with types.MethodType

Upvotes: 4

Related Questions