Last active
January 9, 2024 16:18
-
-
Save ankona/6fc67179766e6af8e96d00f6eb79d003 to your computer and use it in GitHub Desktop.
Demo executing a function within a context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import contextvars | |
import logging | |
import multiprocessing as mp | |
import sys | |
import threading | |
import typing as t | |
logging.basicConfig(stream=sys.stdout, | |
format="%(asctime)s [%(process)d::%(thread)d] %(levelname)s %(name)s %(message)s", | |
level=logging.INFO) | |
logger = logging.getLogger(__name__) | |
ctx_var = contextvars.ContextVar("foo") | |
class ContextThread(threading.Thread): | |
"""Customized Thread that ensures new threads may change context vars""" | |
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: | |
self.ctx = contextvars.copy_context() | |
super().__init__(*args, **kwargs) | |
def run(self) -> None: | |
return self.ctx.run(super().run) | |
def other(desc: str): | |
logger.info(f"other::ctx_var: {ctx_var.get(None)} - {desc}") | |
def main(): | |
ctx_var.set(123) | |
ctx = contextvars.copy_context() | |
logger.info(f"main::ctx_var: {ctx_var.get(None)}") | |
ctx.run(other, desc='ctx.run') | |
p = mp.Process(target=other, args=('mp.Process',)) | |
p.start() | |
p.join() | |
t = threading.Thread(target=other, args=('threading.Thread',)) | |
t.start() | |
t.join() | |
t = ContextThread(target=other, args=('ContextThread',)) | |
t.start() | |
t.join() | |
if __name__ == "__main__": | |
main() |
Author
ankona
commented
Jan 9, 2024
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment