Problem with objects copying each other in memory

dlocpuwons cameron.pulsford at gmail.com
Thu Feb 12 16:57:19 EST 2009


Using Python 2.6.1...

I am (attempting) to make an A* search for a chess problem, but I am
running into a really annoying shared memory issue in my successor
function. Here it is stripped down to the important parts that relate
to my problem.

def successors(self):
		result = []
		moves = [[2, 1], [2, -1], [-2, 1], [-2, -1], [1, 2], [1, -2], [-1,
2], [-1, -2]] #possible moves for a knight

		for i in moves:
			temp = Knight(self.x, self.y, self.g, self.h, self.gp, self.sl)
			temp.x += i[0]
			temp.y += i[1]
			temp.sl.append([temp.x, temp.y]) #Adds the new current state to the
visited states list
			result.append(temp)
		return result

The method creates a temporary Knight object, increments it to the new
position and then adds this new position to its list of visited
states. Then it returns a list of these 8 new objects. The problem
seems to be with the "result.sl.append()" line. As the method chugs
along and creates the new objects the "temp.sl" lines seems to stay in
memory, so when the method is done all the new objects have all the
new states that were made over the course of the method instead of
just their own created in the loop. For example when I try to get
successors for a piece that is initially at (2,2) with no previously
visited states, the method prints this out for the sl (state list)
value

[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]

but what it should print out is

[[2, 2], [4, 3]]
[[2, 2], [4, 1]]
[[2, 2], [0, 3]]
[[2, 2], [0, 1]]
[[2, 2], [3, 4]]
[[2, 2], [3, 0]]
[[2, 2], [1, 4]]
[[2, 2], [1, 0]]

It sort of seems like python is trying to be too smart and is trying
to keep things in memory. Is there anyway to work around this?



More information about the Python-list mailing list