Newbie Python questions: I want to model something that can have a several inter-connected instance variables and if I set one, I want to recalculate the others. Any can be set.
E.g. a circle – each instance has an area, circumference and radius (let’s ignore the diameter). If I set the area, I want the circumference & radius re-calculated and vice-versa. Should I :
class circle:
def area(self):
return cmath.pi*self.radius*self.radius
def circumference(self):
return 2 * cmath.pi * self.radius
def radius(self):
return self.circumference/(2*cmath.pi)
circle1 = circle()
circle1.radius = 5
print "Circle1's area is {0} and its circumference is {1}".format(circle1.area, circle1.circumference)
Now there’s nothing in the code sample to calculate the area once the radius has been set, so do I need @property
with setters and getters for the radius, area and circumference to calculate the other attributes when this one is set or am I barking up completely the wrong tree?
Instead of keeping 3 member fields and synchronizing them, you only need to store one actual value in memory – the radius is a good choice in this example – and always use it:
import cmath
class Circle(object):
def __init__(self, radius=0.0):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, radius):
self._radius = float(radius)
@property
def area(self):
return cmath.pi * self._radius * self._radius
@area.setter
def area(self, area):
self._radius = (area / cmath.pi) ** 0.5
@property
def circumference(self):
return 2 * cmath.pi * self._radius
@circumference.setter
def circumference(self, circumference):
self._radius = circumference / cmath.pi / 2
circle1 = Circle()
circle1.radius = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)
circle1.area = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)
circle1.circumference = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)
This solution seems too obvious though – is there a specific reason you want to have separate member fields? You can usually find a smaller number of values you can calculate the rest from…
7
A fool-proof and robust way of dealing with dependent attributes is to use my small pure-python module exactly for handling acyclic dependencies in python class attributes, also known as dataflow programming.
Sometimes it is not feasible to simply update all attributes when one is changed. Ideally, changing an attribute doesn’t cause any updates. Only getting an attribute should cause updates, and only the required updates.
That is exactly what the module does. It is very easy to implement in any class definition.
For instance, consider an attribute dependency structure shown below:
This dependency structure is completely defined using the library’s descriptors:
class DataflowSuccess():
# The following defines the directed acyclic computation graph for these attributes.
a1 = IndependentAttr(init_value = 1, name = 'a1')
a2 = DeterminantAttr(dependencies = ['a1'], calc_func = 'update_a2', name = 'a2')
a3 = DeterminantAttr(dependencies = ['a2'], calc_func = 'update_a3', name = 'a3')
a4 = DeterminantAttr(dependencies = ['a1','a2'], calc_func = 'update_a4', name = 'a4')
a5 = DeterminantAttr(dependencies = ['a1','a2','a3','a6'], calc_func = 'update_a5', name = 'a5')
a6 = IndependentAttr(init_value = 6, name = 'a6')
a7 = DeterminantAttr(dependencies = ['a4','a5'], calc_func = 'update_a7', name = 'a7')
# ...... define the update functions update_a2, update_a3 etc
def update_a2():
....
The module takes care of the rest. Changing an attribute causes its children (attributes it affects) (and their children, etc) to know their values need to be recalculated in the future. When the value of an attribute is requested by calling __get__
(for instance by executing obj.a5
), only the required updates occur, all automatically behind the scenes.
If it doesn’t suit your needs, at least it is a helpful example of how the descriptor functionalities work. This example is available at the github page. Descriptors provide lots of flexibility for modifying how __get__
and __set__
and __del__
work for your class attributes, which can solve dependency problems.