@@ -10,25 +10,36 @@ def _get_current_context() -> Dict[str, Any]:
1010
1111
1212@contextmanager
13- def new_context ():
13+ def new_context (fresh = False ):
1414 # TODO - we could extend this context idea to also apply to other event types eventually,
1515 # but right now it only applies to exceptions...
1616 """
1717 Create a new context scope that will be active for the duration of the with block.
1818 Any tags set within this scope will be isolated to this context. Any exceptions raised
1919 within the context will be captured and tagged with the context tags.
2020
21- Example:
21+ Args:
22+ fresh: Whether to start with a fresh context (default: False).
23+ If False, inherits tags from parent context.
24+ If True, starts with no tags.
25+
26+ Examples:
27+ # Inherit parent context tags
2228 with posthog.new_context():
2329 posthog.tag("user_id", "123")
24- # The exception will be captured and tagged with the context tags
30+ raise ValueError("Something went wrong")
31+
32+ # Start with fresh context (no inherited tags)
33+ with posthog.new_context(fresh=True):
34+ posthog.tag("user_id", "123")
2535 raise ValueError("Something went wrong")
2636
2737 """
2838 import posthog
2939
40+ current_tags = _get_current_context ().copy ()
3041 current_stack = _context_stack .get ()
31- new_stack = current_stack + [{}]
42+ new_stack = current_stack + [{}] if fresh else current_stack + [ current_tags ]
3243 token = _context_stack .set (new_stack )
3344
3445 try :
@@ -73,28 +84,32 @@ def clear_tags() -> None:
7384F = TypeVar ("F" , bound = Callable [..., Any ])
7485
7586
76- def scoped (func : F ) -> F :
87+ def scoped (fresh = False ) :
7788 """
7889 Decorator that creates a new context for the function, wraps the function in a
7990 try/except block, and if an exception occurs, captures it with the current context
8091 tags before re-raising it.
8192
8293 Args:
83- func: The function to wrap
94+ fresh: Whether to start with a fresh context (default: False)
8495
8596 Example:
86- @posthog.scoped
97+ @posthog.scoped()
8798 def process_payment(payment_id):
8899 posthog.tag("payment_id", payment_id)
89100 posthog.tag("payment_method", "credit_card")
90101 # If this raises an exception, it will be captured with tags
91102 # and then re-raised
92103 """
93- from functools import wraps
94104
95- @wraps (func )
96- def wrapper (* args , ** kwargs ):
97- with new_context ():
98- return func (* args , ** kwargs )
105+ def decorator (func : F ) -> F :
106+ from functools import wraps
107+
108+ @wraps (func )
109+ def wrapper (* args , ** kwargs ):
110+ with new_context (fresh = fresh ):
111+ return func (* args , ** kwargs )
112+
113+ return cast (F , wrapper )
99114
100- return cast ( F , wrapper )
115+ return decorator
0 commit comments