From f1a532806286da1294cfb8d64f81673ceb4c53db Mon Sep 17 00:00:00 2001 From: Yaniv Michael Kaul Date: Mon, 6 Apr 2026 21:43:32 +0300 Subject: [PATCH] perf: skip tuple(partial(...)) construction for empty callbacks/errbacks In _set_final_result and _set_final_exception, skip building the tuple of partial(fn, ...) when the callbacks/errbacks list is empty. Most queries use the synchronous result() path and never register callbacks or errbacks, so this avoids constructing an empty tuple and the associated generator overhead on every query completion. --- cassandra/cluster.py | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/cassandra/cluster.py b/cassandra/cluster.py index 9eace8810d..906af0e69e 100644 --- a/cassandra/cluster.py +++ b/cassandra/cluster.py @@ -4967,16 +4967,21 @@ def _set_final_result(self, response): # -- prevents case where _final_result is set, then a callback is # added and executed on the spot, then executed again as a # registered callback - to_call = tuple( - partial(fn, response, *args, **kwargs) - for (fn, args, kwargs) in self._callbacks - ) + callbacks = self._callbacks + if callbacks: + to_call = tuple( + partial(fn, response, *args, **kwargs) + for (fn, args, kwargs) in callbacks + ) + else: + to_call = None self._event.set() # apply each callback - for callback_partial in to_call: - callback_partial() + if to_call: + for callback_partial in to_call: + callback_partial() def _set_final_exception(self, response): self._cancel_timer() @@ -4989,15 +4994,20 @@ def _set_final_exception(self, response): # prevents case where _final_exception is set, then an errback is # added and executed on the spot, then executed again as a # registered errback - to_call = tuple( - partial(fn, response, *args, **kwargs) - for (fn, args, kwargs) in self._errbacks - ) + errbacks = self._errbacks + if errbacks: + to_call = tuple( + partial(fn, response, *args, **kwargs) + for (fn, args, kwargs) in errbacks + ) + else: + to_call = None self._event.set() # apply each callback - for callback_partial in to_call: - callback_partial() + if to_call: + for callback_partial in to_call: + callback_partial() def _handle_retry_decision(self, retry_decision, response, host):