[Python-ideas] Redefining method

Steven D'Aprano steve at pearwood.info
Mon Jul 30 19:28:28 EDT 2018


On Tue, Jul 31, 2018 at 10:10:32AM +1200, Greg Ewing wrote:
> Jamesie Pic wrote:
> >def o.bar(self): ...
> 
> You could get almost the same effect with
> 
>    from functools import partial
> 
>    def bar(self, other_args):
>       ...
> 
>    o.bar = partial(bar, o)

Why are you using functools.partial instead of types.MethodType? I'm 
wondering if there is some advantage to partial that I don't recognise.

I'm not sure if there's a functional difference between the two 
approaches, but it makes o.bar a different kind of callable and that 
will probably make a difference to somebody.


> But IMO this is nowhere near being a common enough thing to
> do to justify having special syntax for it.

This sort of thing isn't common because there's no neat, easy, obvious, 
built-in way to do it. If we allowed people to extend classes using the 
syntax

    def classobj.methodname(...): ...

    def instance.methodname(...): ...

people would use the technique more. For good or ill.

I don't question the utility of this technique, but I suspect we prefer 
to *slightly* discourage it by *not* providing a Batteries Included 
solution for this. If you want to do this, we won't stop you, but 
neither will we encourage it by supporting it in syntax or providing a 
standard decorator for it.



-- 
Steve


More information about the Python-ideas mailing list