C-Love511 C-Love511 - 1 year ago 65
Python Question

Python shallow/deep copy error

No, this is not a duplicate.

I have the following classes:

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

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
, but when I use
, or write to it, it references the same board for both players.

I even added code to create a
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download