|
2
|
Python has an extremely flexible object model that allows for assignment of arbitrary objects to arbitrary attributes of instances. I would like to do something like this: def button( self ): print "Pressed!" and then assign it to an instance: mywidget.bigred = button and call it: mywidget.bigred() However this doesn't work because the attribute needs to be a bound method, not a function. Also, the name of the installed function remains button (eg. in stack traces), when we would like it to be bigred. This recipe provides the installmethod() and renamefunction() functions to solve this problem.
See the examples above in the __main__ block. Note also that we can install lambda functions (which have no name) and the resulting method will have our given name "listIndex" both as the attribute name and in any subsequent stack traces. I originally wanted to suggest these functions as an addition to the standard new.py module. However this has been deprecated in a very neat way by replacing all the new.py functions with types (as in "from types import ClassType as classobj"). I don't know where installmethod() and renamefunction() might belong in the python distribution now. Any ideas? |
1 comment
Add a comment
Sign in to comment

Download
Copy to clipboard

Use isinstance rather than comparing types. For the sake of robustness I'd suggest using, e.g., isinstance(object, ClassType) rather than type(object) == ClassType.