self modifying code
Robin Becker
robin at NOSPAMreportlab.com
Sat Apr 29 14:04:23 EDT 2006
Peter Otten wrote:
....
>>
>> def func(a):
>> global func, data
>> data = somethingcomplexandcostly()
>> def func(a):
>> return simple(data,a)
>> return func(a)
>>
........
>
> at the cost of just one object identity test whereas your func()
> implementation will do the heavy-lifting every time func() is called in the
> client (unless func() has by chance been invoked as lazymodule.func()
> before the import).
in the example code the heavy lifting, costly(), is done only once as
the function that does it is overwritten. As pointed out it won't work
as simply in a class. Memoisation could improve the performance of the
normal case form of the function ie
def func(a):
return simple(data,a)
but I guess that would depend on whether simple(data,a) is relatively
expensive compared to the costs the memo lookup.
--
Robin Becker
More information about the Python-list
mailing list