[ZODB-Dev] "Advanced ZODB for Python Programmers" article: volatile example
Vincent Pelletier
vincent at nexedi.com
Mon May 24 07:59:50 EDT 2010
Hi.
I think the example on volatile attributes given in "Advanced ZODB for Python
Programmers" article[1] shows a bad practice.
From the article:
if hasattr(self, '_v_image'):
return self._v_image
This should be rewritten as:
try:
return self._v_image
except AttributeError:
This solves cases where _v_ attribute gets garbage-collected between hasattr
call and "return" line. A way to make this obvious is to artificially set
object cache size to 0.
Note that another broken pattern would be to use code like:
self._v_image=expensive_calculation()
return self._v_image
the article advertises the right pattern (using a local variable for return):
image=expensive_calculation()
self._v_image=image
return image
I've been hitting problems with this code pattern many times in the past, and
should have written about it earlier.
[1] http://zodb.org/documentation/articles/ZODB2.html
--
Vincent Pelletier
More information about the ZODB-Dev
mailing list