Recently I\'ve been writing a bunch of code like this:
class A:
def __init__(self, x):
self.x = x
self._y = None
def y(self):
if self._y is
My EAFP pythonista approach is described by the following snippet.
My classes inherit _reset_attributes from WithAttributes and use it to invalidate the scary values.
class WithAttributes:
def _reset_attributes(self, attributes):
assert isinstance(attributes,list)
for attribute in attributes:
try:
delattr(self, '_' + attribute)
except:
pass
class Square(WithAttributes):
def __init__(self, size):
self._size = size
@property
def area(self):
try:
return self._area
except AttributeError:
self._area = self.size * self.size
return self._area
@property
def size(self):
return self._size
@size.setter
def size(self, size):
self._size = size
self._reset_attributes('area')