From d17ee64819047fe5a76db750e530dd78df3b934d Mon Sep 17 00:00:00 2001 From: Laurent Perron Date: Tue, 20 Feb 2024 12:20:30 +0100 Subject: [PATCH] fix #4902 --- .../samples/vrp_solution_callback.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/ortools/constraint_solver/samples/vrp_solution_callback.py b/ortools/constraint_solver/samples/vrp_solution_callback.py index 4fd79bfa97..b1b4d65f29 100755 --- a/ortools/constraint_solver/samples/vrp_solution_callback.py +++ b/ortools/constraint_solver/samples/vrp_solution_callback.py @@ -24,6 +24,8 @@ """ # [START import] +import weakref + from ortools.constraint_solver import routing_enums_pb2 from ortools.constraint_solver import pywrapcp # [END import] @@ -98,20 +100,21 @@ class SolutionCallback: model: pywrapcp.RoutingModel, limit: int, ): - self._routing_manager = manager - self._routing_model = model + # We need a weak ref on the routing model to avoid a cycle. + self._routing_manager_ref = weakref.ref(manager) + self._routing_model_ref = weakref.ref(model) self._counter = 0 self._counter_limit = limit self.objectives = [] def __call__(self): - objective = int(self._routing_model.CostVar().Value()) + objective = int(self._routing_model_ref().CostVar().Value()) if not self.objectives or objective < self.objectives[-1]: self.objectives.append(objective) - print_solution(self._routing_manager, self._routing_model) + print_solution(self._routing_manager_ref(), self._routing_model_ref()) self._counter += 1 if self._counter > self._counter_limit: - self._routing_model.solver().FinishCurrentSearch() + self._routing_model_ref().solver().FinishCurrentSearch() # [END solution_callback]