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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4