0
# Scope Management
1
2
Context management through a three-tier scope system providing isolation and data organization across global, request, and local levels with hierarchical inheritance and thread-safe operations.
3
4
## Capabilities
5
6
### Scope Access
7
8
Access the three levels of scopes for reading and modifying context data with proper isolation guarantees.
9
10
```python { .api }
11
def get_global_scope() -> Scope:
12
"""
13
Get the global scope containing process-wide data.
14
15
The global scope contains data that applies to all events in the process,
16
such as release version, environment, and server-specific context.
17
18
Returns:
19
Scope: The global scope instance
20
"""
21
22
def get_isolation_scope() -> Scope:
23
"""
24
Get the isolation scope containing request/user-level data.
25
26
The isolation scope isolates data between different requests, users,
27
or logical operations. Integrations typically manage this scope.
28
29
Returns:
30
Scope: The current isolation scope instance
31
"""
32
33
def get_current_scope() -> Scope:
34
"""
35
Get the current local scope containing thread/context-specific data.
36
37
The current scope contains data specific to the current execution context,
38
such as span-specific tags, local breadcrumbs, and temporary context.
39
40
Returns:
41
Scope: The current local scope instance
42
"""
43
```
44
45
**Usage Examples:**
46
47
```python
48
import sentry_sdk
49
50
# Set global application data
51
global_scope = sentry_sdk.get_global_scope()
52
global_scope.set_tag("service", "payment-processor")
53
global_scope.set_context("app", {
54
"version": "1.2.3",
55
"build": "abc123",
56
"environment": "production"
57
})
58
59
# Set request-specific data (typically done by integrations)
60
isolation_scope = sentry_sdk.get_isolation_scope()
61
isolation_scope.set_user({"id": "user_123", "email": "user@example.com"})
62
isolation_scope.set_tag("request_id", "req_456")
63
64
# Set local context data
65
current_scope = sentry_sdk.get_current_scope()
66
current_scope.set_tag("operation", "process_payment")
67
current_scope.add_breadcrumb({
68
"message": "Starting payment validation",
69
"level": "info",
70
"category": "payment"
71
})
72
```
73
74
### Scope Context Managers
75
76
Create isolated scope contexts for temporary modifications without affecting parent scopes.
77
78
```python { .api }
79
def new_scope() -> ContextManager[Scope]:
80
"""
81
Create a new local scope context manager.
82
83
The new scope inherits from the current scope but modifications
84
are isolated and don't affect the parent scope.
85
86
Returns:
87
ContextManager[Scope]: Context manager yielding the new scope
88
"""
89
90
def isolation_scope() -> ContextManager[Scope]:
91
"""
92
Create a new isolation scope context manager.
93
94
Creates a fresh isolation scope for request/user isolation.
95
Typically used by web framework integrations.
96
97
Returns:
98
ContextManager[Scope]: Context manager yielding the isolation scope
99
"""
100
```
101
102
**Usage Examples:**
103
104
```python
105
import sentry_sdk
106
107
# Temporary scope for specific operation
108
def process_batch(items):
109
with sentry_sdk.new_scope() as scope:
110
scope.set_tag("batch_size", len(items))
111
scope.set_extra("batch_id", "batch_123")
112
113
for item in items:
114
try:
115
process_item(item)
116
except Exception:
117
# Exception captured with batch context
118
sentry_sdk.capture_exception()
119
120
# Isolation for user request (typically done by web frameworks)
121
def handle_request(request):
122
with sentry_sdk.isolation_scope() as scope:
123
scope.set_user({
124
"id": request.user.id,
125
"email": request.user.email,
126
"ip_address": request.remote_addr
127
})
128
scope.set_tag("endpoint", request.path)
129
130
# All events in this context include user data
131
return process_request(request)
132
```
133
134
## Scope Hierarchy
135
136
### Inheritance Model
137
138
Scopes follow a hierarchical inheritance model where child scopes inherit data from parent scopes:
139
140
1. **Global Scope** (bottom layer): Process-wide data
141
2. **Isolation Scope** (middle layer): Request/user data
142
3. **Current Scope** (top layer): Local context data
143
144
When an event is captured, data is merged from all three scopes with higher levels taking precedence for conflicting keys.
145
146
### Scope Levels
147
148
**Global Scope:**
149
- Release version and environment
150
- Server and deployment information
151
- Application-wide configuration
152
- Global tags and context
153
154
**Isolation Scope:**
155
- User identification and session data
156
- Request metadata and correlation IDs
157
- Per-request configuration overrides
158
- Request-specific context
159
160
**Current Scope:**
161
- Span and transaction-specific data
162
- Local breadcrumbs and temporary context
163
- Function-level tags and metadata
164
- Short-lived contextual information
165
166
## Scope Class Interface
167
168
### Core Scope Methods
169
170
```python { .api }
171
class Scope:
172
# User and identification
173
def set_user(self, value: Optional[Dict[str, Any]]) -> None:
174
"""Set user information for events."""
175
176
# Tags for filtering and searching
177
def set_tag(self, key: str, value: str) -> None:
178
"""Set a single tag key-value pair."""
179
180
def set_tags(self, tags: Dict[str, str]) -> None:
181
"""Set multiple tags at once."""
182
183
def remove_tag(self, key: str) -> None:
184
"""Remove a tag by key."""
185
186
# Extra data for debugging
187
def set_extra(self, key: str, value: Any) -> None:
188
"""Set extra debug information."""
189
190
def remove_extra(self, key: str) -> None:
191
"""Remove extra data by key."""
192
193
# Structured context objects
194
def set_context(self, key: str, value: Dict[str, Any]) -> None:
195
"""Set structured context data."""
196
197
def remove_context(self, key: str) -> None:
198
"""Remove context data by key."""
199
200
# Breadcrumb trail
201
def add_breadcrumb(
202
self,
203
crumb: Optional[Dict[str, Any]] = None,
204
hint: Optional[Dict[str, Any]] = None,
205
**kwargs
206
) -> None:
207
"""Add a breadcrumb to the trail."""
208
209
def clear_breadcrumbs(self) -> None:
210
"""Clear all breadcrumbs."""
211
212
# Event capture
213
def capture_exception(
214
self,
215
error: Optional[BaseException] = None,
216
**kwargs
217
) -> Optional[str]:
218
"""Capture exception with this scope's context."""
219
220
def capture_message(
221
self,
222
message: str,
223
level: Optional[str] = None,
224
**kwargs
225
) -> Optional[str]:
226
"""Capture message with this scope's context."""
227
228
# Scope management
229
def fork(self) -> Scope:
230
"""Create a copy of this scope."""
231
232
def clear(self) -> None:
233
"""Clear all data from this scope."""
234
235
def update_from_scope(self, scope: Scope) -> None:
236
"""Update this scope with data from another scope."""
237
```
238
239
### Scope Properties
240
241
```python { .api }
242
class Scope:
243
@property
244
def level(self) -> Optional[str]:
245
"""Current log level."""
246
247
@level.setter
248
def level(self, value: Optional[str]) -> None:
249
"""Set log level."""
250
251
@property
252
def user(self) -> Optional[Dict[str, Any]]:
253
"""Current user data."""
254
255
@user.setter
256
def user(self, value: Optional[Dict[str, Any]]) -> None:
257
"""Set user data."""
258
259
@property
260
def transaction(self) -> Optional[str]:
261
"""Current transaction name."""
262
263
@transaction.setter
264
def transaction(self, value: Optional[str]) -> None:
265
"""Set transaction name."""
266
267
@property
268
def span(self) -> Optional[Span]:
269
"""Current active span."""
270
271
@span.setter
272
def span(self, value: Optional[Span]) -> None:
273
"""Set active span."""
274
```
275
276
## Best Practices
277
278
### Scope Usage Patterns
279
280
**Global Scope:**
281
- Set once during application initialization
282
- Use for data that never changes during process lifetime
283
- Avoid frequent modifications (performance impact)
284
285
**Isolation Scope:**
286
- Managed primarily by framework integrations
287
- Use for request/user/session boundaries
288
- Clear between logical operations
289
290
**Current Scope:**
291
- Use for temporary, local context
292
- Leverage context managers for automatic cleanup
293
- Safe for frequent modifications
294
295
### Context Isolation
296
297
```python
298
# Good: Proper isolation for concurrent operations
299
async def handle_multiple_requests():
300
tasks = []
301
for request_data in requests:
302
task = asyncio.create_task(process_with_isolation(request_data))
303
tasks.append(task)
304
await asyncio.gather(*tasks)
305
306
async def process_with_isolation(request_data):
307
with sentry_sdk.isolation_scope() as scope:
308
scope.set_user(request_data.user)
309
scope.set_tag("request_id", request_data.id)
310
# Process request with isolated context
311
return await process_request(request_data)
312
```
313
314
### Memory Management
315
316
Scopes automatically manage memory by:
317
- Limiting breadcrumb storage (configurable via `max_breadcrumbs`)
318
- Cleaning up temporary scopes when context managers exit
319
- Garbage collecting unused scope references
320
- Implementing efficient copy-on-write for scope inheritance