CONSTRUCT - Python's way of Ruby's "alias_method"

Ilias Lazaridis ilias at lazaridis.com
Fri Jun 9 11:14:08 EDT 2006


Maric Michaud wrote:
> Le Jeudi 08 Juin 2006 14:28, Ilias Lazaridis a écrit :
>> Another possibility is to enlink (hook?) the functionality into an
>> existent function
>>
>> Is there any way (beside a patch) to alter the behaviour to an existing
>> function. Is ther a python construct similar to the "alias_method" of Ruby:
>>
> No, there is no special construct to do this, but we do things very similar 
> every day in Zope, it's called "monkey patch" :
> 
> #patch_service.py
> from toto import service
> 
> def my_impl(self, *args) :
> 	old_result = self._old_method(*args)
> 	# ...
> 	return new_result
> 
> if not hasattr(service, '_old_method') :
> 	service._old_method = service.method
> 	service.method = my_impl
> 
> once this file is imported, all future calls to "method" of service instances 
> will use my_impl.

Ok, just a small problem when a _function_ is to be hooked.

Looking a the code in the debugger shows that the function "syncdb" is 
correctly overridden. But when the code returns, "syncdb" has again it's 
original value.

Can I import "syncdb" by reference instead by value, thus the change 
'survives'?

#------------------------------------------------------------------------------

#syncdb_hook.py

from django.rework.evolve   import evolvedb
from django.core.management import syncdb

def syncdb_new(*args) :
     evolvedb()
     syncdb_result = syncdb_old(*args)
     return syncdb_result

if syncdb != syncdb_new:
     syncdb_old = syncdb
     syncdb = syncdb_new

.

-- 
http://lazaridis.com



More information about the Python-list mailing list