diff --git a/setup.py b/setup.py index ca8c91c..32ec8e7 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ long_description_content_type="text/markdown", packages=find_packages(), package_data={"": ["py.typed"]}, - python_requires=">=3.6", + python_requires=">=3.7", # contextvars install_requires=["boto3 >= 1.9", "typing-extensions >= 3.7",], # it is important to keep these install_requires basically in sync with the Pipfile as well. ) diff --git a/tests/xoto3/utils/stack_context_test.py b/tests/xoto3/utils/stack_context_test.py index b698757..a5e6a08 100644 --- a/tests/xoto3/utils/stack_context_test.py +++ b/tests/xoto3/utils/stack_context_test.py @@ -1,5 +1,6 @@ from contextvars import ContextVar from datetime import datetime +from multiprocessing.pool import ThreadPool from xoto3.utils.oncall_default import OnCallDefault from xoto3.utils.stack_context import StackContext, stack_context, unwrap @@ -67,3 +68,25 @@ def g(): with ConsistentReadContext.set(True): assert g() is True assert g() is False + + +NumberContext = ContextVar("Number", default=-1) + + +def test_threaded_stack_context(): + """The idea behind context vars is that each thread gets its own + without anyone having to use thread.locals directly, and when paired with stack_context, + you can have nested contexts easily within the same thread. + """ + vals = list(range(10)) + + def extract_from_context(): + return NumberContext.get() + + def put_in_context(val): + with stack_context(NumberContext, val): + return extract_from_context() + + out = ThreadPool(3).map(put_in_context, vals) + + assert out == vals