[Python-Dev] 2.6 idea: a 'function' builtin to parallel classmethod and staticmethod

Guido van Rossum guido at python.org
Sun Aug 13 04:33:17 CEST 2006


It ought to be called @instancemethod for a better analogy.

PS Nick how's the book coming along? :-)

--Guido

On 8/11/06, Nick Coghlan <ncoghlan at iinet.net.au> wrote:
> It's sometimes useful to be able to use an existing callable as a method of a
> new class. If the callable is a real function, this is easy. You just
> including the following line in the class definition:
>
>    method = some_callable
>
> However, callable objects without a function-like __get__ method can't be used
> that way. So, to avoid a dependency on an implementation detail of
> some_callable (i.e. whether or not it is a true function object), you have to
> write:
>
>
>    def method():
>        return some_callable()
>
> (and you can lose useful metadata in the process!)
>
> However, if you're adding a callable as a class method or static method, there
> is OOWTDI:
>
>    method = classmethod(some_callable)
>    method = staticmethod(some_callable)
>
> It would be nice if there was a similar mechanism for normal instance methods
> as well:
>
>    method = function(some_callable)
>
> This came up during the PEP 343 implementation - "context =
> contextlib.closing" is a tempting thing to write in order to provide a
> "x.context()" method for use in a with statement, but it doesn't actually work
> properly (because closing is a class, not a function).
>
> Similarly, you can't create a method simply by applying functools.partial to
> an existing function - the result won't have a __get__ method, so it will be
> treated like a normal attribute instead of as an instance method.
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
> ---------------------------------------------------------------
>              http://www.boredomandlaziness.org
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: http://mail.python.org/mailman/options/python-dev/guido%40python.org
>


-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list