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

Nick Coghlan ncoghlan at iinet.net.au
Sat Aug 12 04:47:10 CEST 2006

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 

   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 

   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.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list