[Tutor] Prevent "Coder's Remorse"?

Alan G alan.gauld at freenet.co.uk
Wed Sep 28 16:48:47 CEST 2005

> pointList = [
> {lat:40.123,lon:-81.456, 
>    'attributes':{'msg':'example','beavers':34, 'distance':18.132}
> },
> {lat:40.12345,lon:-81.45678, 
>    'attributes':{'msg':'','beavers':0, 'distance':0.0}
> }
> ]

THis sopunds like its crying out for a class

class Point:
   def __init__(self, lat, long, msg, beavers, distance):
      self.lat = lat
      self.long = long

Pointlist = [Point(40.123,-81.456,'example',34,18.132),

> If I add an attribute of 'newAtt':'newVal' to
> pointList[1]['attributes'], I want it to automatically add
> 'newAtt':'default' to all the other member's 'attributes' 
> dictionary. 

You could do that by calling a class method that updates all 
of the instances.

> If I delete an attribute, it should delete from all the 
> member's dictionaries. 

Likewise a class method could do this.

> attributes are limited to string, integer, and float values.

Doesn't really matter! :-)

> Is there an elegant approach that occurs to anyone? 
> Is there a data structure that forces all members to have the same
> keys? 

A class. Although in Python its always possible to add 
instance variables but you have to do it deliberately!
But at least a class will ensure that all the values 
that should be there are indeed present.

> Is there an object structure that will let updates to one instance
> affect all instances?

A class method is the traditional way of doing that. 
Get the init method to update a global (or class based) 
list of instances and write a del() method that removes 

Then a class method can iterate that instance list 
doing whatever it needs to do...


Alan G.

More information about the Tutor mailing list