I'm struggling with the best way to implement the following in python:
I have a simulation that generates a variety of shapes. At each run of the simulation code, new shapes composed of new line objects are generated, but these objects need to be persistent across multiple runs.
Each line is described by a polyline-encoded string. Each time a new line is generated I need to verify that the same line doesn't already exists. If it does, I want to return the original, if not, I want to create a new one.
I also need to keep track of all created objects so that at the end of multiple simulation runs, I can get them all back and send them to a database.
My first approach is to use the itertools.count iterator as a class variable, and get a new id on creation (I need to keep both the id and string for legacy reasons).
class Line(object):
new_id = itertools.count(start=1).next
lines = []
def __init__(self, coord_string):
self.coord_string = coord_string
self.id = Line.new_id()
Line.lines.append(self)
@staticmethod
def from_coord_string(coord_string):
lines = [l.coord_string for l in Line.lines]
try:
ind = lines.index(path)
return Line.links(ind)
except ValueError:
return Line(coord_string)
I'm also keeping track of all created objects in the a class variable. This lets me check to see if a Line has been created already, or get easy access to all of them later, i.e.:
all_lines = Line.lines
dump_to_db(all_lines)
What are the downsides to using class variables like this? Is there a better, or more efficient way to implement this?
idgeneration isn't thread safe, so it's totally possible to end up with 2o objects with the same line.