C-Love511 C-Love511 - 22 days ago 5
Python Question

Python shallow/deep copy error

No, this is not a duplicate.

I have the following classes:
-Board
-Player

When Player is instantiated, it creates a new board object for that player.

I have a function which switches the current and latent players:

from copy import deepcopy


switch_players(self):
temp_val = deepcopy(self.current_player)
# self.current_player = None
self.current_player = deepcopy(self.latent_player)
# self.latent_player = None
self.latent_player = deepcopy(temp_val)
temp_val = None


This works fine for the players' names when I call
self.current_player.name
, but when I use
self.current_player.board.display
, or write to it, it references the same board for both players.

I even added code to create a
deepcopy()
of the board to switch like this, but I'm still experiencing the same issue. Is this a fundamentally wrong way to do something like this? Or is this approach correct, and I should look elsewhere in my code? (I have another way of doing this, but I'm not understanding the theory behind why this current approach doesn't work.)

Answer

It works so, because name is string, board is class instance which will be copied, but it is one level deeper, so it will not be copied with deepcopy. Deepcopy is not meant recursively.