Skip to content

Commit c7fec7e

Browse files
authored
Merge pull request #125 from alex-pewpew/main
Refactor conditional loading of ThreadPoolExecutor
2 parents 573f048 + 737906f commit c7fec7e

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

awslambdaric/lambda_runtime_client.py

+8-3
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,12 @@ class LambdaRuntimeClient(object):
5252
def __init__(self, lambda_runtime_address, use_thread_for_polling_next=False):
5353
self.lambda_runtime_address = lambda_runtime_address
5454
self.use_thread_for_polling_next = use_thread_for_polling_next
55+
if self.use_thread_for_polling_next:
56+
# Conditionally import only for the case when TPE is used in this class.
57+
from concurrent.futures import ThreadPoolExecutor
58+
59+
# Not defining symbol as global to avoid relying on TPE being imported unconditionally.
60+
self.ThreadPoolExecutor = ThreadPoolExecutor
5561

5662
def post_init_error(self, error_response_data):
5763
# These imports are heavy-weight. They implicitly trigger `import ssl, hashlib`.
@@ -74,9 +80,8 @@ def wait_next_invocation(self):
7480
# which can then process signals.
7581
if self.use_thread_for_polling_next:
7682
try:
77-
from concurrent.futures import ThreadPoolExecutor
78-
79-
with ThreadPoolExecutor(max_workers=1) as executor:
83+
# TPE class is supposed to be registered at construction time and be ready to use.
84+
with self.ThreadPoolExecutor(max_workers=1) as executor:
8085
future = executor.submit(runtime_client.next)
8186
response_body, headers = future.result()
8287
except Exception as e:

tests/test_bootstrap.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -589,10 +589,11 @@ def raise_exception_handler(json_input, lambda_context):
589589

590590
self.assertEqual(mock_stdout.getvalue(), error_logs)
591591

592-
@patch("sys.stdout", new_callable=StringIO)
592+
# The order of patches matter. Using MagicMock resets sys.stdout to the default.
593593
@patch("importlib.import_module")
594+
@patch("sys.stdout", new_callable=StringIO)
594595
def test_handle_event_request_fault_exception_logging_syntax_error(
595-
self, mock_import_module, mock_stdout
596+
self, mock_stdout, mock_import_module
596597
):
597598
try:
598599
eval("-")

0 commit comments

Comments
 (0)