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

Ilias Lazaridis ilias at lazaridis.com
Fri Jun 9 14:06:46 EDT 2006


Duncan Booth wrote:
> 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.

ok, I understand.

the code below works, but has the limitation that I cannot import the 
syncdb_hook within "django.core.management".

There is no way to import/get "syncdb" but mutable?

>> #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

works fine.

.

-- 
http://lazaridis.com



More information about the Python-list mailing list