CONSTRUCT - Python's way of Ruby's "alias_method"
Duncan Booth
duncan.booth at invalid.invalid
Fri Jun 9 13:42:09 EDT 2006
Ilias Lazaridis wrote:
>> #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'?
The difference is that Maric imported the module. To make the change affect
the original model you have to access the function as an attribute of its
module, not by importing the function from the module.
>
> #----------------------------------------------------------------------
> --------
>
> #syncdb_hook.py
>
> from django.rework.evolve import evolvedb
> from django.core.management import syncdb
from django.core import management
>
> def syncdb_new(*args) :
> evolvedb()
> syncdb_result = syncdb_old(*args)
> return syncdb_result
>
> if syncdb != syncdb_new:
> syncdb_old = syncdb
> syncdb = syncdb_new
>
if management.syncdb != syncdb_new:
syncdb_old = management.syncdb
management.syncdb = syncdb_new
More information about the Python-list
mailing list