Python: Redefining Function From Within The Function
Solution 1:
This is overly complicated. Instead, use memoization:
def memoized(f):
res = []
def resf():
if len(res) == 0
res.append(f())
return res[0]
return resf
and then simply
@memoized
def f():
# expensive calculation here ...
return calculated_value
In Python 3, you can replace memoized with functools.lru_cache.
Solution 2:
Simply add global f at the beginning of the f function, otherwise python creates a local f variable.
Solution 3:
Changing f in f's scope doesn't affect outside of function, if you want to change f, you could use global:
>>> def f():
... print(1)
... global f
... f=lambda: print(2)
...
>>> f()
1
>>> f()
2
>>> f()
2
Solution 4:
You can use memoization and decoration to cache the result. See an example here. A separate question on memoization that might prove useful can be found here.
Solution 5:
What you're describing is the kind of problem caching was invented for. Why not just have a buffer to hold the result; before doing the expensive calculation, check if the buffer is already filled; if so, return the buffered result, otherwise, execute the calculation, fill the buffer, and then return the result. No need to go all fancy with self-modifying code for this.
Post a Comment for "Python: Redefining Function From Within The Function"