0

I am working on an inventory simulation model. I have this global list variable called current_batches which consists of objects of a custom class Batch and is used to keep track of the current inventory. While running the simulation, a number of functions use this current_batches variable and modify it following certain events in the simulation.

Inside one function, I need to copy this variable and do some operations with the objects of the obtained copy, without modifying the objects of the original list. I used copy.deepcopy() and it works, but it is very slow and I will be running the simulation for many products with many iterations. Therefore, I was wondering if there is a way to copy this (global) list variable without using copy.deepcopy().

I briefly looked at the pickle module, but it was unclear to me whether this module was useful in my situation.

NS13
  • 11
  • 4
  • If modifications are small you can try to keep track of them and reverse afterwards. Make some `to_undo` array and keep there reverse operations to what you do with `current_batches`. – dankal444 Nov 01 '22 at 15:51
  • Second option is to simplify Batch class to something what will be more easy (faster) to deepcopy. Also look [at this answer](https://stackoverflow.com/a/39414002/4601890) – dankal444 Nov 01 '22 at 15:54

1 Answers1

0

If you need a full deepcopy which takes time because the copied object is large I see no way to avoid it.

I suggest you speed things up creating a current_batches_update object where you save the modifications only and adjust the logic of the code to get values not present in current_batches_update object from the current_batches one. This way you can avoid making a full copy keeping the ability to get all the values.

Another option would be to equip current_batches with the ability to store two versions for some of its values, so you can store the special modified ones as a second version in current_batches and allow version (=1 or =2)` as parameter in the function for retrieving the values designed to deliver version 1 if there is no requested version 2.

Claudio
  • 7,474
  • 3
  • 18
  • 48