Fw: What is Python good for?

Ken Seehof kseehof at neuralintegrator.com
Thu Sep 13 07:26:36 EDT 2001


> On Wed, 12 Sep 2001, Ken Seehof wrote:
>
> > Oh yes, the overall effect is definitely "ooh-ahh".  I was
> > just commenting that I haven't noticed any specific unique
> > python features that are "ooh-ahh".
>
> Here's something that came up recently that if it doesn't make you go
> "ooh-ahh", then it will make you go "whoa":
>
> ---
> >>> def a():
> ...   return 'abc'
> ...
> >>> def b():
> ...   return 123
> ...
> >>> a.func_code=b.func_code
> >>> a()
> 123
> Ignacio Vazquez-Abrams  <ignacio at openservices.net>

Whoa.  Check this out (python 2.1 or later required):

from __future__ import nested_scopes  # if this is python 2.1

def enhance_method(klass, method_name, replacement):
    'replace a class instance method'
    method = getattr(klass, method_name)
    setattr(klass, method_name, new.instancemethod(
        lambda *args, **kwds: replacement(method, *args, **kwds),
        None, klass))
 
This replaces a method in an existing class with a function that takes the
original method as an argument.  The replacement function is of the form:

def replacement(old_method, self, *args, **kwds):
   ...
   r = old_method(self, *args, **kwds)
   ...
   return r

Enjoy,
- Ken
 






More information about the Python-list mailing list