Re: self modifying code
- From: Peter Otten <__peter__@xxxxxx>
- Date: Sat, 29 Apr 2006 19:36:12 +0200
Robin Becker wrote:
When young I was warned repeatedly by more knowledgeable folk that self
modifying code was dangerous.
Is the following idiom dangerous or unpythonic?
def func(a):
global func, data
data = somethingcomplexandcostly()
def func(a):
return simple(data,a)
return func(a)
It could be replaced by
data = somethingcomplexandcostly()
def func(a):
return simple(data,a)
but this always calculates data.
Consider
data = None
def func(a):
global data
if data is None:
data = costly()
return simple(data, a)
if you want lazy evaluation. Not only is it easier to understand,
it also works with
from lazymodule import func
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).
Peter
.
- Follow-Ups:
- Re: self modifying code
- From: Robin Becker
- Re: self modifying code
- References:
- self modifying code
- From: Robin Becker
- self modifying code
- Prev by Date: Re: self modifying code
- Next by Date: Re: How to get computer name
- Previous by thread: Re: self modifying code
- Next by thread: Re: self modifying code
- Index(es):
Relevant Pages
|