Skip to content

Commit 33271c8

Browse files
⚡️ Speed up method JsonErrorMessageParser._try_get_error by 25% in PR #44010 (pnilan/airbyte-cdk-improve-error-messages-parsing)
Certainly! To optimize the given code, especially focusing on runtime improvements, we can. 1. Replace the list comprehension and generator used in the `_try_get_error` method with more efficient alternatives. 2. Optimize the dictionary look-up to check keys sequentially rather than getting values multiple times. Here's the revised code.
1 parent 13f48c9 commit 33271c8

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

airbyte-cdk/python/airbyte_cdk/sources/streams/http/error_handlers/json_error_message_parser.py

+20-17
Original file line numberDiff line numberDiff line change
@@ -14,24 +14,27 @@ def _try_get_error(self, value: Optional[JsonType]) -> Optional[str]:
1414
if isinstance(value, str):
1515
return value
1616
elif isinstance(value, list):
17-
errors_in_value = [self._try_get_error(v) for v in value]
18-
return ", ".join(v for v in errors_in_value if v is not None)
17+
# Using filter to avoid generating the intermediate list
18+
errors = filter(None, map(self._try_get_error, value))
19+
return ", ".join(errors)
1920
elif isinstance(value, dict):
20-
new_value = (
21-
value.get("message")
22-
or value.get("messages")
23-
or value.get("error")
24-
or value.get("errors")
25-
or value.get("failures")
26-
or value.get("failure")
27-
or value.get("detail")
28-
or value.get("err")
29-
or value.get("error_message")
30-
or value.get("msg")
31-
or value.get("reason")
32-
or value.get("status_message")
33-
)
34-
return self._try_get_error(new_value)
21+
# Check keys sequentially and return the first non-None error message
22+
for key in (
23+
"message",
24+
"messages",
25+
"error",
26+
"errors",
27+
"failures",
28+
"failure",
29+
"detail",
30+
"err",
31+
"error_message",
32+
"msg",
33+
"reason",
34+
"status_message",
35+
):
36+
if key in value:
37+
return self._try_get_error(value[key])
3538
return None
3639

3740
def parse_response_error_message(self, response: requests.Response) -> Optional[str]:

0 commit comments

Comments
 (0)