5 ms·
I've previously used hasattr() to check for the existence of an attribute qua instance variable to lazy-load and cache that attribute def kdtree(self):
by jjgreen 11y ago
I've previously used hasattr() to check for the existence of an attribute qua instance variable to lazy-load and cache that attribute
def kdtree(self):
if not hasattr(self, '_kdtree'):
self._kdtree = scipy.spatial.KDTree(self.xi.T)
return self._kdtree
like ruby's
@foo ||= expensive_calculation
is there a better way?
- jimmytucson 11y ago> ruby's Perl has //= (http://perldoc.perl.org/perlop.html#Assignment-Operators http://perldoc.perl.org/perlop.html#Assignment-Operators)
- dietrichepp 11y agoWell, you can do it this way: def kdtree(self): try: return self._kdtree except AttributeError: pass self._kdtree = scipy.spatial.KDTree(self.xi.T) return self._kdtree And, of course, you could do all of that with a decorator.
- scrollaway 11y agoIn this particular case you should initialize self._kdtree to None in __init__, and just check if self._kdtree is None: <calculate>
- jjgreen 11y agoAh, nice, thanks
- craigds 11y agoWorks great unless None is a valid value for the thing, in which case you'll recalculate it every time. If that was the case you should just use hasattr().
- rbanffy 11y agoOr try and except AttributeError. Exceptions are a good thing.
- jjgreen 11y agoI went with this decorator in the end, works a treat! https://github.com/jjgreen/mvpoly/blob/master/src/python/mvpoly/util/cached_property.py https://github.com/jjgreen/mvpoly/blob/master/src/python/mvp...