sentry-sdk 3.0.0a2__py2.py3-none-any.whl → 3.0.0a4__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of sentry-sdk might be problematic. Click here for more details.

Files changed (159) hide show
  1. sentry_sdk/__init__.py +4 -0
  2. sentry_sdk/_compat.py +5 -12
  3. sentry_sdk/_init_implementation.py +7 -7
  4. sentry_sdk/_log_batcher.py +17 -29
  5. sentry_sdk/_lru_cache.py +7 -9
  6. sentry_sdk/_queue.py +2 -4
  7. sentry_sdk/_types.py +9 -16
  8. sentry_sdk/_werkzeug.py +5 -7
  9. sentry_sdk/ai/monitoring.py +45 -33
  10. sentry_sdk/ai/utils.py +8 -5
  11. sentry_sdk/api.py +91 -87
  12. sentry_sdk/attachments.py +10 -12
  13. sentry_sdk/client.py +119 -159
  14. sentry_sdk/consts.py +432 -223
  15. sentry_sdk/crons/api.py +16 -17
  16. sentry_sdk/crons/decorator.py +25 -27
  17. sentry_sdk/debug.py +4 -6
  18. sentry_sdk/envelope.py +46 -112
  19. sentry_sdk/feature_flags.py +9 -15
  20. sentry_sdk/integrations/__init__.py +24 -19
  21. sentry_sdk/integrations/_asgi_common.py +16 -18
  22. sentry_sdk/integrations/_wsgi_common.py +22 -33
  23. sentry_sdk/integrations/aiohttp.py +33 -31
  24. sentry_sdk/integrations/anthropic.py +43 -38
  25. sentry_sdk/integrations/argv.py +3 -4
  26. sentry_sdk/integrations/ariadne.py +16 -18
  27. sentry_sdk/integrations/arq.py +20 -29
  28. sentry_sdk/integrations/asgi.py +63 -37
  29. sentry_sdk/integrations/asyncio.py +15 -17
  30. sentry_sdk/integrations/asyncpg.py +1 -1
  31. sentry_sdk/integrations/atexit.py +6 -10
  32. sentry_sdk/integrations/aws_lambda.py +26 -36
  33. sentry_sdk/integrations/beam.py +10 -18
  34. sentry_sdk/integrations/boto3.py +20 -18
  35. sentry_sdk/integrations/bottle.py +25 -34
  36. sentry_sdk/integrations/celery/__init__.py +40 -59
  37. sentry_sdk/integrations/celery/beat.py +22 -26
  38. sentry_sdk/integrations/celery/utils.py +15 -17
  39. sentry_sdk/integrations/chalice.py +8 -10
  40. sentry_sdk/integrations/clickhouse_driver.py +22 -32
  41. sentry_sdk/integrations/cloud_resource_context.py +9 -16
  42. sentry_sdk/integrations/cohere.py +19 -25
  43. sentry_sdk/integrations/dedupe.py +5 -8
  44. sentry_sdk/integrations/django/__init__.py +69 -74
  45. sentry_sdk/integrations/django/asgi.py +25 -33
  46. sentry_sdk/integrations/django/caching.py +24 -20
  47. sentry_sdk/integrations/django/middleware.py +18 -21
  48. sentry_sdk/integrations/django/signals_handlers.py +12 -11
  49. sentry_sdk/integrations/django/templates.py +21 -18
  50. sentry_sdk/integrations/django/transactions.py +16 -11
  51. sentry_sdk/integrations/django/views.py +8 -12
  52. sentry_sdk/integrations/dramatiq.py +21 -21
  53. sentry_sdk/integrations/excepthook.py +10 -10
  54. sentry_sdk/integrations/executing.py +3 -4
  55. sentry_sdk/integrations/falcon.py +27 -42
  56. sentry_sdk/integrations/fastapi.py +13 -16
  57. sentry_sdk/integrations/flask.py +31 -38
  58. sentry_sdk/integrations/gcp.py +13 -16
  59. sentry_sdk/integrations/gnu_backtrace.py +7 -20
  60. sentry_sdk/integrations/gql.py +16 -17
  61. sentry_sdk/integrations/graphene.py +14 -13
  62. sentry_sdk/integrations/grpc/__init__.py +3 -2
  63. sentry_sdk/integrations/grpc/aio/client.py +2 -2
  64. sentry_sdk/integrations/grpc/aio/server.py +15 -14
  65. sentry_sdk/integrations/grpc/client.py +21 -11
  66. sentry_sdk/integrations/grpc/consts.py +2 -0
  67. sentry_sdk/integrations/grpc/server.py +12 -8
  68. sentry_sdk/integrations/httpx.py +11 -14
  69. sentry_sdk/integrations/huey.py +14 -21
  70. sentry_sdk/integrations/huggingface_hub.py +17 -17
  71. sentry_sdk/integrations/langchain.py +204 -114
  72. sentry_sdk/integrations/launchdarkly.py +13 -10
  73. sentry_sdk/integrations/litestar.py +40 -38
  74. sentry_sdk/integrations/logging.py +29 -36
  75. sentry_sdk/integrations/loguru.py +16 -20
  76. sentry_sdk/integrations/modules.py +3 -4
  77. sentry_sdk/integrations/openai.py +421 -204
  78. sentry_sdk/integrations/openai_agents/__init__.py +49 -0
  79. sentry_sdk/integrations/openai_agents/consts.py +1 -0
  80. sentry_sdk/integrations/openai_agents/patches/__init__.py +4 -0
  81. sentry_sdk/integrations/openai_agents/patches/agent_run.py +152 -0
  82. sentry_sdk/integrations/openai_agents/patches/models.py +52 -0
  83. sentry_sdk/integrations/openai_agents/patches/runner.py +42 -0
  84. sentry_sdk/integrations/openai_agents/patches/tools.py +84 -0
  85. sentry_sdk/integrations/openai_agents/spans/__init__.py +5 -0
  86. sentry_sdk/integrations/openai_agents/spans/agent_workflow.py +20 -0
  87. sentry_sdk/integrations/openai_agents/spans/ai_client.py +46 -0
  88. sentry_sdk/integrations/openai_agents/spans/execute_tool.py +47 -0
  89. sentry_sdk/integrations/openai_agents/spans/handoff.py +24 -0
  90. sentry_sdk/integrations/openai_agents/spans/invoke_agent.py +41 -0
  91. sentry_sdk/integrations/openai_agents/utils.py +153 -0
  92. sentry_sdk/integrations/openfeature.py +12 -8
  93. sentry_sdk/integrations/pure_eval.py +6 -10
  94. sentry_sdk/integrations/pymongo.py +14 -18
  95. sentry_sdk/integrations/pyramid.py +31 -36
  96. sentry_sdk/integrations/quart.py +23 -28
  97. sentry_sdk/integrations/ray.py +73 -64
  98. sentry_sdk/integrations/redis/__init__.py +7 -4
  99. sentry_sdk/integrations/redis/_async_common.py +18 -12
  100. sentry_sdk/integrations/redis/_sync_common.py +16 -15
  101. sentry_sdk/integrations/redis/modules/caches.py +17 -8
  102. sentry_sdk/integrations/redis/modules/queries.py +9 -8
  103. sentry_sdk/integrations/redis/rb.py +3 -2
  104. sentry_sdk/integrations/redis/redis.py +4 -4
  105. sentry_sdk/integrations/redis/redis_cluster.py +10 -8
  106. sentry_sdk/integrations/redis/redis_py_cluster_legacy.py +3 -2
  107. sentry_sdk/integrations/redis/utils.py +21 -22
  108. sentry_sdk/integrations/rq.py +13 -16
  109. sentry_sdk/integrations/rust_tracing.py +10 -7
  110. sentry_sdk/integrations/sanic.py +34 -46
  111. sentry_sdk/integrations/serverless.py +22 -27
  112. sentry_sdk/integrations/socket.py +29 -17
  113. sentry_sdk/integrations/spark/__init__.py +1 -0
  114. sentry_sdk/integrations/spark/spark_driver.py +45 -83
  115. sentry_sdk/integrations/spark/spark_worker.py +7 -11
  116. sentry_sdk/integrations/sqlalchemy.py +22 -19
  117. sentry_sdk/integrations/starlette.py +89 -93
  118. sentry_sdk/integrations/starlite.py +31 -37
  119. sentry_sdk/integrations/statsig.py +5 -4
  120. sentry_sdk/integrations/stdlib.py +32 -28
  121. sentry_sdk/integrations/strawberry.py +63 -50
  122. sentry_sdk/integrations/sys_exit.py +7 -11
  123. sentry_sdk/integrations/threading.py +13 -15
  124. sentry_sdk/integrations/tornado.py +28 -32
  125. sentry_sdk/integrations/trytond.py +4 -3
  126. sentry_sdk/integrations/typer.py +8 -6
  127. sentry_sdk/integrations/unleash.py +5 -4
  128. sentry_sdk/integrations/wsgi.py +47 -46
  129. sentry_sdk/logger.py +13 -9
  130. sentry_sdk/monitor.py +16 -28
  131. sentry_sdk/opentelemetry/consts.py +11 -4
  132. sentry_sdk/opentelemetry/contextvars_context.py +17 -15
  133. sentry_sdk/opentelemetry/propagator.py +38 -21
  134. sentry_sdk/opentelemetry/sampler.py +51 -34
  135. sentry_sdk/opentelemetry/scope.py +46 -37
  136. sentry_sdk/opentelemetry/span_processor.py +43 -59
  137. sentry_sdk/opentelemetry/tracing.py +32 -12
  138. sentry_sdk/opentelemetry/utils.py +180 -196
  139. sentry_sdk/profiler/continuous_profiler.py +108 -97
  140. sentry_sdk/profiler/transaction_profiler.py +70 -97
  141. sentry_sdk/profiler/utils.py +11 -15
  142. sentry_sdk/scope.py +251 -264
  143. sentry_sdk/scrubber.py +22 -26
  144. sentry_sdk/serializer.py +48 -65
  145. sentry_sdk/session.py +44 -61
  146. sentry_sdk/sessions.py +35 -49
  147. sentry_sdk/spotlight.py +15 -21
  148. sentry_sdk/tracing.py +118 -184
  149. sentry_sdk/tracing_utils.py +103 -123
  150. sentry_sdk/transport.py +131 -157
  151. sentry_sdk/utils.py +278 -309
  152. sentry_sdk/worker.py +16 -28
  153. {sentry_sdk-3.0.0a2.dist-info → sentry_sdk-3.0.0a4.dist-info}/METADATA +1 -1
  154. sentry_sdk-3.0.0a4.dist-info/RECORD +168 -0
  155. sentry_sdk-3.0.0a2.dist-info/RECORD +0 -154
  156. {sentry_sdk-3.0.0a2.dist-info → sentry_sdk-3.0.0a4.dist-info}/WHEEL +0 -0
  157. {sentry_sdk-3.0.0a2.dist-info → sentry_sdk-3.0.0a4.dist-info}/entry_points.txt +0 -0
  158. {sentry_sdk-3.0.0a2.dist-info → sentry_sdk-3.0.0a4.dist-info}/licenses/LICENSE +0 -0
  159. {sentry_sdk-3.0.0a2.dist-info → sentry_sdk-3.0.0a4.dist-info}/top_level.txt +0 -0
sentry_sdk/scope.py CHANGED
@@ -1,3 +1,4 @@
1
+ from __future__ import annotations
1
2
  import os
2
3
  import sys
3
4
  import warnings
@@ -38,27 +39,31 @@ from sentry_sdk.utils import (
38
39
  event_from_exception,
39
40
  exc_info_from_error,
40
41
  logger,
42
+ safe_str,
41
43
  )
42
44
 
43
45
  from typing import TYPE_CHECKING
44
46
 
45
47
  if TYPE_CHECKING:
46
- from collections.abc import Mapping, MutableMapping
48
+ from typing import (
49
+ Any,
50
+ Callable,
51
+ Deque,
52
+ Dict,
53
+ Generator,
54
+ Iterator,
55
+ List,
56
+ Optional,
57
+ ParamSpec,
58
+ Tuple,
59
+ TypeVar,
60
+ Union,
61
+ Self,
62
+ )
47
63
 
48
- from typing import Any
49
- from typing import Callable
50
- from typing import Deque
51
- from typing import Dict
52
- from typing import Generator
53
- from typing import Iterator
54
- from typing import List
55
- from typing import Optional
56
- from typing import ParamSpec
57
- from typing import Tuple
58
- from typing import TypeVar
59
- from typing import Union
60
- from typing import Self
64
+ from collections.abc import Mapping, MutableMapping
61
65
 
66
+ import sentry_sdk
62
67
  from sentry_sdk._types import (
63
68
  Breadcrumb,
64
69
  BreadcrumbHint,
@@ -71,8 +76,6 @@ if TYPE_CHECKING:
71
76
  Type,
72
77
  )
73
78
 
74
- import sentry_sdk
75
-
76
79
  P = ParamSpec("P")
77
80
  R = TypeVar("R")
78
81
 
@@ -84,7 +87,7 @@ if TYPE_CHECKING:
84
87
  # In case this is a http server (think web framework) with multiple users
85
88
  # the data will be added to events of all users.
86
89
  # Typically this is used for process wide data such as the release.
87
- _global_scope = None # type: Optional[Scope]
90
+ _global_scope: Optional[Scope] = None
88
91
 
89
92
  # Holds data for the active request.
90
93
  # This is used to isolate data for different requests or users.
@@ -96,7 +99,7 @@ _isolation_scope = ContextVar("isolation_scope", default=None)
96
99
  # This can be used to manually add additional data to a span.
97
100
  _current_scope = ContextVar("current_scope", default=None)
98
101
 
99
- global_event_processors = [] # type: List[EventProcessor]
102
+ global_event_processors: List[EventProcessor] = []
100
103
 
101
104
 
102
105
  class ScopeType(Enum):
@@ -106,21 +109,17 @@ class ScopeType(Enum):
106
109
  MERGED = "merged"
107
110
 
108
111
 
109
- def add_global_event_processor(processor):
110
- # type: (EventProcessor) -> None
112
+ def add_global_event_processor(processor: EventProcessor) -> None:
111
113
  global_event_processors.append(processor)
112
114
 
113
115
 
114
- def _attr_setter(fn):
115
- # type: (Any) -> Any
116
+ def _attr_setter(fn: Any) -> Any:
116
117
  return property(fset=fn, doc=fn.__doc__)
117
118
 
118
119
 
119
- def _disable_capture(fn):
120
- # type: (F) -> F
120
+ def _disable_capture(fn: F) -> F:
121
121
  @wraps(fn)
122
- def wrapper(self, *args, **kwargs):
123
- # type: (Any, *Dict[str, Any], **Any) -> Any
122
+ def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
124
123
  if not self._should_capture:
125
124
  return
126
125
  try:
@@ -172,31 +171,29 @@ class Scope:
172
171
  "_flags",
173
172
  )
174
173
 
175
- def __init__(self, ty=None):
176
- # type: (Optional[ScopeType]) -> None
174
+ def __init__(self, ty: Optional[ScopeType] = None) -> None:
177
175
  self._type = ty
178
176
 
179
- self._event_processors = [] # type: List[EventProcessor]
180
- self._error_processors = [] # type: List[ErrorProcessor]
177
+ self._event_processors: List[EventProcessor] = []
178
+ self._error_processors: List[ErrorProcessor] = []
181
179
 
182
- self._name = None # type: Optional[str]
183
- self._propagation_context = None # type: Optional[PropagationContext]
184
- self._n_breadcrumbs_truncated = 0 # type: int
180
+ self._name: Optional[str] = None
181
+ self._propagation_context: Optional[PropagationContext] = None
182
+ self._n_breadcrumbs_truncated: int = 0
185
183
 
186
- self.client = NonRecordingClient() # type: sentry_sdk.client.BaseClient
184
+ self.client: sentry_sdk.client.BaseClient = NonRecordingClient()
187
185
 
188
186
  self.clear()
189
187
 
190
188
  incoming_trace_information = self._load_trace_data_from_env()
191
189
  self.generate_propagation_context(incoming_data=incoming_trace_information)
192
190
 
193
- def __copy__(self):
194
- # type: () -> Self
191
+ def __copy__(self) -> Self:
195
192
  """
196
193
  Returns a copy of this scope.
197
194
  This also creates a copy of all referenced data structures.
198
195
  """
199
- rv = object.__new__(self.__class__) # type: Self
196
+ rv: Self = object.__new__(self.__class__)
200
197
 
201
198
  rv._type = self._type
202
199
  rv.client = self.client
@@ -232,8 +229,7 @@ class Scope:
232
229
  return rv
233
230
 
234
231
  @classmethod
235
- def get_current_scope(cls):
236
- # type: () -> Scope
232
+ def get_current_scope(cls) -> Scope:
237
233
  """
238
234
  .. versionadded:: 2.0.0
239
235
 
@@ -247,16 +243,14 @@ class Scope:
247
243
  return current_scope
248
244
 
249
245
  @classmethod
250
- def _get_current_scope(cls):
251
- # type: () -> Optional[Scope]
246
+ def _get_current_scope(cls) -> Optional[Scope]:
252
247
  """
253
248
  Returns the current scope without creating a new one. Internal use only.
254
249
  """
255
250
  return _current_scope.get()
256
251
 
257
252
  @classmethod
258
- def set_current_scope(cls, new_current_scope):
259
- # type: (Scope) -> None
253
+ def set_current_scope(cls, new_current_scope: Scope) -> None:
260
254
  """
261
255
  .. versionadded:: 2.0.0
262
256
 
@@ -266,8 +260,7 @@ class Scope:
266
260
  _current_scope.set(new_current_scope)
267
261
 
268
262
  @classmethod
269
- def get_isolation_scope(cls):
270
- # type: () -> Scope
263
+ def get_isolation_scope(cls) -> Scope:
271
264
  """
272
265
  .. versionadded:: 2.0.0
273
266
 
@@ -281,16 +274,14 @@ class Scope:
281
274
  return isolation_scope
282
275
 
283
276
  @classmethod
284
- def _get_isolation_scope(cls):
285
- # type: () -> Optional[Scope]
277
+ def _get_isolation_scope(cls) -> Optional[Scope]:
286
278
  """
287
279
  Returns the isolation scope without creating a new one. Internal use only.
288
280
  """
289
281
  return _isolation_scope.get()
290
282
 
291
283
  @classmethod
292
- def set_isolation_scope(cls, new_isolation_scope):
293
- # type: (Scope) -> None
284
+ def set_isolation_scope(cls, new_isolation_scope: Scope) -> None:
294
285
  """
295
286
  .. versionadded:: 2.0.0
296
287
 
@@ -300,8 +291,7 @@ class Scope:
300
291
  _isolation_scope.set(new_isolation_scope)
301
292
 
302
293
  @classmethod
303
- def get_global_scope(cls):
304
- # type: () -> Scope
294
+ def get_global_scope(cls) -> Scope:
305
295
  """
306
296
  .. versionadded:: 2.0.0
307
297
 
@@ -314,8 +304,7 @@ class Scope:
314
304
  return _global_scope
315
305
 
316
306
  @classmethod
317
- def last_event_id(cls):
318
- # type: () -> Optional[str]
307
+ def last_event_id(cls) -> Optional[str]:
319
308
  """
320
309
  .. versionadded:: 2.2.0
321
310
 
@@ -330,8 +319,11 @@ class Scope:
330
319
  """
331
320
  return cls.get_isolation_scope()._last_event_id
332
321
 
333
- def _merge_scopes(self, additional_scope=None, additional_scope_kwargs=None):
334
- # type: (Optional[Scope], Optional[Dict[str, Any]]) -> Self
322
+ def _merge_scopes(
323
+ self,
324
+ additional_scope: Optional[Scope] = None,
325
+ additional_scope_kwargs: Optional[Dict[str, Any]] = None,
326
+ ) -> Self:
335
327
  """
336
328
  Merges global, isolation and current scope into a new scope and
337
329
  adds the given additional scope or additional scope kwargs to it.
@@ -366,8 +358,7 @@ class Scope:
366
358
  return final_scope
367
359
 
368
360
  @classmethod
369
- def get_client(cls):
370
- # type: () -> sentry_sdk.client.BaseClient
361
+ def get_client(cls) -> sentry_sdk.client.BaseClient:
371
362
  """
372
363
  .. versionadded:: 2.0.0
373
364
 
@@ -393,18 +384,18 @@ class Scope:
393
384
  if client is not None and client.is_active():
394
385
  return client
395
386
 
396
- try:
397
- client = _global_scope.client # type: ignore
398
- except AttributeError:
399
- client = None
387
+ if _global_scope:
388
+ try:
389
+ client = _global_scope.client
390
+ except AttributeError:
391
+ client = None
400
392
 
401
393
  if client is not None and client.is_active():
402
394
  return client
403
395
 
404
396
  return NonRecordingClient()
405
397
 
406
- def set_client(self, client=None):
407
- # type: (Optional[sentry_sdk.client.BaseClient]) -> None
398
+ def set_client(self, client: Optional[sentry_sdk.client.BaseClient] = None) -> None:
408
399
  """
409
400
  .. versionadded:: 2.0.0
410
401
 
@@ -416,8 +407,7 @@ class Scope:
416
407
  """
417
408
  self.client = client if client is not None else NonRecordingClient()
418
409
 
419
- def fork(self):
420
- # type: () -> Self
410
+ def fork(self) -> Self:
421
411
  """
422
412
  .. versionadded:: 2.0.0
423
413
 
@@ -426,8 +416,7 @@ class Scope:
426
416
  forked_scope = copy(self)
427
417
  return forked_scope
428
418
 
429
- def _load_trace_data_from_env(self):
430
- # type: () -> Optional[Dict[str, str]]
419
+ def _load_trace_data_from_env(self) -> Optional[Dict[str, str]]:
431
420
  """
432
421
  Load Sentry trace id and baggage from environment variables.
433
422
  Can be disabled by setting SENTRY_USE_ENVIRONMENT to "false".
@@ -453,15 +442,15 @@ class Scope:
453
442
 
454
443
  return incoming_trace_information or None
455
444
 
456
- def set_new_propagation_context(self):
457
- # type: () -> None
445
+ def set_new_propagation_context(self) -> None:
458
446
  """
459
447
  Creates a new propagation context and sets it as `_propagation_context`. Overwriting existing one.
460
448
  """
461
449
  self._propagation_context = PropagationContext()
462
450
 
463
- def generate_propagation_context(self, incoming_data=None):
464
- # type: (Optional[Dict[str, str]]) -> None
451
+ def generate_propagation_context(
452
+ self, incoming_data: Optional[dict[str, str]] = None
453
+ ) -> None:
465
454
  """
466
455
  Makes sure the propagation context is set on the scope.
467
456
  If there is `incoming_data` overwrite existing propagation context.
@@ -476,16 +465,14 @@ class Scope:
476
465
  if self._propagation_context is None:
477
466
  self.set_new_propagation_context()
478
467
 
479
- def get_dynamic_sampling_context(self):
480
- # type: () -> Optional[Dict[str, str]]
468
+ def get_dynamic_sampling_context(self) -> Optional[Dict[str, str]]:
481
469
  """
482
470
  Returns the Dynamic Sampling Context from the baggage or populates one.
483
471
  """
484
472
  baggage = self.get_baggage()
485
473
  return baggage.dynamic_sampling_context() if baggage else None
486
474
 
487
- def get_traceparent(self, *args, **kwargs):
488
- # type: (Any, Any) -> Optional[str]
475
+ def get_traceparent(self, *args: Any, **kwargs: Any) -> Optional[str]:
489
476
  """
490
477
  Returns the Sentry "sentry-trace" header (aka the traceparent) from the
491
478
  currently active span or the scopes Propagation Context.
@@ -507,8 +494,7 @@ class Scope:
507
494
  # Fall back to isolation scope's traceparent. It always has one
508
495
  return self.get_isolation_scope().get_traceparent()
509
496
 
510
- def get_baggage(self, *args, **kwargs):
511
- # type: (Any, Any) -> Optional[Baggage]
497
+ def get_baggage(self, *args: Any, **kwargs: Any) -> Optional[Baggage]:
512
498
  """
513
499
  Returns the Sentry "baggage" header containing trace information from the
514
500
  currently active span or the scopes Propagation Context.
@@ -534,25 +520,23 @@ class Scope:
534
520
  # Fall back to isolation scope's baggage. It always has one
535
521
  return self.get_isolation_scope().get_baggage()
536
522
 
537
- def get_trace_context(self):
538
- # type: () -> Any
523
+ def get_trace_context(self) -> Any:
539
524
  """
540
525
  Returns the Sentry "trace" context from the Propagation Context.
541
526
  """
542
527
  if self._propagation_context is None:
543
528
  return None
544
529
 
545
- trace_context = {
530
+ trace_context: Dict[str, Any] = {
546
531
  "trace_id": self._propagation_context.trace_id,
547
532
  "span_id": self._propagation_context.span_id,
548
533
  "parent_span_id": self._propagation_context.parent_span_id,
549
534
  "dynamic_sampling_context": self.get_dynamic_sampling_context(),
550
- } # type: Dict[str, Any]
535
+ }
551
536
 
552
537
  return trace_context
553
538
 
554
- def trace_propagation_meta(self, *args, **kwargs):
555
- # type: (*Any, **Any) -> str
539
+ def trace_propagation_meta(self, *args: Any, **kwargs: Any) -> str:
556
540
  """
557
541
  Return meta tags which should be injected into HTML templates
558
542
  to allow propagation of trace information.
@@ -575,8 +559,7 @@ class Scope:
575
559
 
576
560
  return meta
577
561
 
578
- def iter_headers(self):
579
- # type: () -> Iterator[Tuple[str, str]]
562
+ def iter_headers(self) -> Iterator[Tuple[str, str]]:
580
563
  """
581
564
  Creates a generator which returns the `sentry-trace` and `baggage` headers from the Propagation Context.
582
565
  """
@@ -589,8 +572,9 @@ class Scope:
589
572
  if baggage is not None:
590
573
  yield BAGGAGE_HEADER_NAME, baggage.serialize()
591
574
 
592
- def iter_trace_propagation_headers(self, *args, **kwargs):
593
- # type: (Any, Any) -> Generator[Tuple[str, str], None, None]
575
+ def iter_trace_propagation_headers(
576
+ self, *args: Any, **kwargs: Any
577
+ ) -> Generator[Tuple[str, str], None, None]:
594
578
  """
595
579
  Return HTTP headers which allow propagation of trace data.
596
580
 
@@ -624,8 +608,7 @@ class Scope:
624
608
  for header in isolation_scope.iter_headers():
625
609
  yield header
626
610
 
627
- def get_active_propagation_context(self):
628
- # type: () -> Optional[PropagationContext]
611
+ def get_active_propagation_context(self) -> Optional[PropagationContext]:
629
612
  if self._propagation_context is not None:
630
613
  return self._propagation_context
631
614
 
@@ -639,37 +622,35 @@ class Scope:
639
622
 
640
623
  return None
641
624
 
642
- def clear(self):
643
- # type: () -> None
625
+ def clear(self) -> None:
644
626
  """Clears the entire scope."""
645
- self._level = None # type: Optional[LogLevelStr]
646
- self._fingerprint = None # type: Optional[List[str]]
647
- self._transaction = None # type: Optional[str]
648
- self._transaction_info = {} # type: MutableMapping[str, str]
649
- self._user = None # type: Optional[Dict[str, Any]]
627
+ self._level: Optional[LogLevelStr] = None
628
+ self._fingerprint: Optional[List[str]] = None
629
+ self._transaction: Optional[str] = None
630
+ self._transaction_info: MutableMapping[str, str] = {}
631
+ self._user: Optional[Dict[str, Any]] = None
650
632
 
651
- self._tags = {} # type: Dict[str, Any]
652
- self._contexts = {} # type: Dict[str, Dict[str, Any]]
653
- self._extras = {} # type: MutableMapping[str, Any]
654
- self._attachments = [] # type: List[Attachment]
633
+ self._tags: Dict[str, Any] = {}
634
+ self._contexts: Dict[str, Dict[str, Any]] = {}
635
+ self._extras: MutableMapping[str, Any] = {}
636
+ self._attachments: List[Attachment] = []
655
637
 
656
638
  self.clear_breadcrumbs()
657
- self._should_capture = True # type: bool
639
+ self._should_capture: bool = True
658
640
 
659
- self._span = None # type: Optional[Span]
660
- self._session = None # type: Optional[Session]
661
- self._force_auto_session_tracking = None # type: Optional[bool]
641
+ self._span: Optional[Span] = None
642
+ self._session: Optional[Session] = None
643
+ self._force_auto_session_tracking: Optional[bool] = None
662
644
 
663
- self._profile = None # type: Optional[Profile]
645
+ self._profile: Optional[Profile] = None
664
646
 
665
647
  self._propagation_context = None
666
648
 
667
649
  # self._last_event_id is only applicable to isolation scopes
668
- self._last_event_id = None # type: Optional[str]
669
- self._flags = None # type: Optional[FlagBuffer]
650
+ self._last_event_id: Optional[str] = None
651
+ self._flags: Optional[FlagBuffer] = None
670
652
 
671
- def set_level(self, value):
672
- # type: (LogLevelStr) -> None
653
+ def set_level(self, value: LogLevelStr) -> None:
673
654
  """
674
655
  Sets the level for the scope.
675
656
 
@@ -678,22 +659,19 @@ class Scope:
678
659
  self._level = value
679
660
 
680
661
  @_attr_setter
681
- def fingerprint(self, value):
682
- # type: (Optional[List[str]]) -> None
662
+ def fingerprint(self, value: Optional[List[str]]) -> None:
683
663
  """When set this overrides the default fingerprint."""
684
664
  self._fingerprint = value
685
665
 
686
666
  @property
687
- def root_span(self):
688
- # type: () -> Optional[Span]
667
+ def root_span(self) -> Optional[Span]:
689
668
  """Return the root span in the scope, if any."""
690
669
  if self._span is None:
691
670
  return None
692
671
 
693
672
  return self._span.root_span
694
673
 
695
- def set_transaction_name(self, name, source=None):
696
- # type: (str, Optional[str]) -> None
674
+ def set_transaction_name(self, name: str, source: Optional[str] = None) -> None:
697
675
  """Set the transaction name and optionally the transaction source."""
698
676
  self._transaction = name
699
677
 
@@ -706,17 +684,14 @@ class Scope:
706
684
  self._transaction_info["source"] = source
707
685
 
708
686
  @property
709
- def transaction_name(self):
710
- # type: () -> Optional[str]
687
+ def transaction_name(self) -> Optional[str]:
711
688
  return self._transaction
712
689
 
713
690
  @property
714
- def transaction_source(self):
715
- # type: () -> Optional[str]
691
+ def transaction_source(self) -> Optional[str]:
716
692
  return self._transaction_info.get("source")
717
693
 
718
- def set_user(self, value):
719
- # type: (Optional[Dict[str, Any]]) -> None
694
+ def set_user(self, value: Optional[Dict[str, Any]]) -> None:
720
695
  """Sets a user for the scope."""
721
696
  self._user = value
722
697
  session = self.get_isolation_scope()._session
@@ -724,24 +699,20 @@ class Scope:
724
699
  session.update(user=value)
725
700
 
726
701
  @property
727
- def span(self):
728
- # type: () -> Optional[Span]
702
+ def span(self) -> Optional[Span]:
729
703
  """Get current tracing span."""
730
704
  return self._span
731
705
 
732
706
  @property
733
- def profile(self):
734
- # type: () -> Optional[Profile]
707
+ def profile(self) -> Optional[Profile]:
735
708
  return self._profile
736
709
 
737
710
  @profile.setter
738
- def profile(self, profile):
739
- # type: (Optional[Profile]) -> None
711
+ def profile(self, profile: Optional[Profile]) -> None:
740
712
 
741
713
  self._profile = profile
742
714
 
743
- def set_tag(self, key, value):
744
- # type: (str, Any) -> None
715
+ def set_tag(self, key: str, value: Any) -> None:
745
716
  """
746
717
  Sets a tag for a key to a specific value.
747
718
 
@@ -751,8 +722,7 @@ class Scope:
751
722
  """
752
723
  self._tags[key] = value
753
724
 
754
- def set_tags(self, tags):
755
- # type: (Mapping[str, object]) -> None
725
+ def set_tags(self, tags: Mapping[str, object]) -> None:
756
726
  """Sets multiple tags at once.
757
727
 
758
728
  This method updates multiple tags at once. The tags are passed as a dictionary
@@ -770,8 +740,7 @@ class Scope:
770
740
  """
771
741
  self._tags.update(tags)
772
742
 
773
- def remove_tag(self, key):
774
- # type: (str) -> None
743
+ def remove_tag(self, key: str) -> None:
775
744
  """
776
745
  Removes a specific tag.
777
746
 
@@ -781,53 +750,46 @@ class Scope:
781
750
 
782
751
  def set_context(
783
752
  self,
784
- key, # type: str
785
- value, # type: Dict[str, Any]
786
- ):
787
- # type: (...) -> None
753
+ key: str,
754
+ value: Dict[str, Any],
755
+ ) -> None:
788
756
  """
789
757
  Binds a context at a certain key to a specific value.
790
758
  """
791
759
  self._contexts[key] = value
792
760
 
793
761
  def remove_context(
794
- self, key # type: str
795
- ):
796
- # type: (...) -> None
762
+ self,
763
+ key: str,
764
+ ) -> None:
797
765
  """Removes a context."""
798
766
  self._contexts.pop(key, None)
799
767
 
800
768
  def set_extra(
801
769
  self,
802
- key, # type: str
803
- value, # type: Any
804
- ):
805
- # type: (...) -> None
770
+ key: str,
771
+ value: Any,
772
+ ) -> None:
806
773
  """Sets an extra key to a specific value."""
807
774
  self._extras[key] = value
808
775
 
809
- def remove_extra(
810
- self, key # type: str
811
- ):
812
- # type: (...) -> None
776
+ def remove_extra(self, key: str) -> None:
813
777
  """Removes a specific extra key."""
814
778
  self._extras.pop(key, None)
815
779
 
816
- def clear_breadcrumbs(self):
817
- # type: () -> None
780
+ def clear_breadcrumbs(self) -> None:
818
781
  """Clears breadcrumb buffer."""
819
- self._breadcrumbs = deque() # type: Deque[Breadcrumb]
782
+ self._breadcrumbs: Deque[Breadcrumb] = deque()
820
783
  self._n_breadcrumbs_truncated = 0
821
784
 
822
785
  def add_attachment(
823
786
  self,
824
- bytes=None, # type: Union[None, bytes, Callable[[], bytes]]
825
- filename=None, # type: Optional[str]
826
- path=None, # type: Optional[str]
827
- content_type=None, # type: Optional[str]
828
- add_to_transactions=False, # type: bool
829
- ):
830
- # type: (...) -> None
787
+ bytes: Union[None, bytes, Callable[[], bytes]] = None,
788
+ filename: Optional[str] = None,
789
+ path: Optional[str] = None,
790
+ content_type: Optional[str] = None,
791
+ add_to_transactions: bool = False,
792
+ ) -> None:
831
793
  """Adds an attachment to future events sent from this scope.
832
794
 
833
795
  The parameters are the same as for the :py:class:`sentry_sdk.attachments.Attachment` constructor.
@@ -842,8 +804,12 @@ class Scope:
842
804
  )
843
805
  )
844
806
 
845
- def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
846
- # type: (Optional[Breadcrumb], Optional[BreadcrumbHint], Any) -> None
807
+ def add_breadcrumb(
808
+ self,
809
+ crumb: Optional[Breadcrumb] = None,
810
+ hint: Optional[BreadcrumbHint] = None,
811
+ **kwargs: Any,
812
+ ) -> None:
847
813
  """
848
814
  Adds a breadcrumb.
849
815
 
@@ -861,12 +827,12 @@ class Scope:
861
827
  before_breadcrumb = client.options.get("before_breadcrumb")
862
828
  max_breadcrumbs = client.options.get("max_breadcrumbs", DEFAULT_MAX_BREADCRUMBS)
863
829
 
864
- crumb = dict(crumb or ()) # type: Breadcrumb
830
+ crumb: Breadcrumb = dict(crumb or ())
865
831
  crumb.update(kwargs)
866
832
  if not crumb:
867
833
  return
868
834
 
869
- hint = dict(hint or ()) # type: Hint
835
+ hint: Hint = dict(hint or ())
870
836
 
871
837
  if crumb.get("timestamp") is None:
872
838
  crumb["timestamp"] = datetime.now(timezone.utc)
@@ -887,8 +853,7 @@ class Scope:
887
853
  self._breadcrumbs.popleft()
888
854
  self._n_breadcrumbs_truncated += 1
889
855
 
890
- def start_transaction(self, **kwargs):
891
- # type: (Any) -> Union[NoOpSpan, Span]
856
+ def start_transaction(self, **kwargs: Any) -> Union[NoOpSpan, Span]:
892
857
  """
893
858
  .. deprecated:: 3.0.0
894
859
  This function is deprecated and will be removed in a future release.
@@ -901,8 +866,7 @@ class Scope:
901
866
  )
902
867
  return NoOpSpan(**kwargs)
903
868
 
904
- def start_span(self, **kwargs):
905
- # type: (Any) -> Union[NoOpSpan, Span]
869
+ def start_span(self, **kwargs: Any) -> Union[NoOpSpan, Span]:
906
870
  """
907
871
  Start a span whose parent is the currently active span, if any.
908
872
 
@@ -915,16 +879,22 @@ class Scope:
915
879
  return NoOpSpan(**kwargs)
916
880
 
917
881
  @contextmanager
918
- def continue_trace(self, environ_or_headers):
919
- # type: (Dict[str, Any]) -> Generator[None, None, None]
882
+ def continue_trace(
883
+ self, environ_or_headers: Dict[str, Any]
884
+ ) -> Generator[None, None, None]:
920
885
  """
921
886
  Sets the propagation context from environment or headers to continue an incoming trace.
922
887
  """
923
888
  self.generate_propagation_context(environ_or_headers)
924
889
  yield
925
890
 
926
- def capture_event(self, event, hint=None, scope=None, **scope_kwargs):
927
- # type: (Event, Optional[Hint], Optional[Scope], Any) -> Optional[str]
891
+ def capture_event(
892
+ self,
893
+ event: Event,
894
+ hint: Optional[Hint] = None,
895
+ scope: Optional[Scope] = None,
896
+ **scope_kwargs: Any,
897
+ ) -> Optional[str]:
928
898
  """
929
899
  Captures an event.
930
900
 
@@ -955,8 +925,13 @@ class Scope:
955
925
 
956
926
  return event_id
957
927
 
958
- def capture_message(self, message, level=None, scope=None, **scope_kwargs):
959
- # type: (str, Optional[LogLevelStr], Optional[Scope], Any) -> Optional[str]
928
+ def capture_message(
929
+ self,
930
+ message: str,
931
+ level: Optional[LogLevelStr] = None,
932
+ scope: Optional[Scope] = None,
933
+ **scope_kwargs: Any,
934
+ ) -> Optional[str]:
960
935
  """
961
936
  Captures a message.
962
937
 
@@ -979,15 +954,19 @@ class Scope:
979
954
  if level is None:
980
955
  level = "info"
981
956
 
982
- event = {
957
+ event: Event = {
983
958
  "message": message,
984
959
  "level": level,
985
- } # type: Event
960
+ }
986
961
 
987
962
  return self.capture_event(event, scope=scope, **scope_kwargs)
988
963
 
989
- def capture_exception(self, error=None, scope=None, **scope_kwargs):
990
- # type: (Optional[Union[BaseException, ExcInfo]], Optional[Scope], Any) -> Optional[str]
964
+ def capture_exception(
965
+ self,
966
+ error: Optional[Union[BaseException, ExcInfo]] = None,
967
+ scope: Optional[Scope] = None,
968
+ **scope_kwargs: Any,
969
+ ) -> Optional[str]:
991
970
  """Captures an exception.
992
971
 
993
972
  :param error: An exception to capture. If `None`, `sys.exc_info()` will be used.
@@ -1020,8 +999,7 @@ class Scope:
1020
999
 
1021
1000
  return None
1022
1001
 
1023
- def start_session(self, *args, **kwargs):
1024
- # type: (*Any, **Any) -> None
1002
+ def start_session(self, *args: Any, **kwargs: Any) -> None:
1025
1003
  """Starts a new session."""
1026
1004
  session_mode = kwargs.pop("session_mode", "application")
1027
1005
 
@@ -1035,8 +1013,7 @@ class Scope:
1035
1013
  session_mode=session_mode,
1036
1014
  )
1037
1015
 
1038
- def end_session(self, *args, **kwargs):
1039
- # type: (*Any, **Any) -> None
1016
+ def end_session(self, *args: Any, **kwargs: Any) -> None:
1040
1017
  """Ends the current session if there is one."""
1041
1018
  session = self._session
1042
1019
  self._session = None
@@ -1045,8 +1022,7 @@ class Scope:
1045
1022
  session.close()
1046
1023
  self.get_client().capture_session(session)
1047
1024
 
1048
- def stop_auto_session_tracking(self, *args, **kwargs):
1049
- # type: (*Any, **Any) -> None
1025
+ def stop_auto_session_tracking(self, *args: Any, **kwargs: Any) -> None:
1050
1026
  """Stops automatic session tracking.
1051
1027
 
1052
1028
  This temporarily session tracking for the current scope when called.
@@ -1055,18 +1031,14 @@ class Scope:
1055
1031
  self.end_session()
1056
1032
  self._force_auto_session_tracking = False
1057
1033
 
1058
- def resume_auto_session_tracking(self):
1059
- # type: (...) -> None
1034
+ def resume_auto_session_tracking(self) -> None:
1060
1035
  """Resumes automatic session tracking for the current scope if
1061
1036
  disabled earlier. This requires that generally automatic session
1062
1037
  tracking is enabled.
1063
1038
  """
1064
1039
  self._force_auto_session_tracking = None
1065
1040
 
1066
- def add_event_processor(
1067
- self, func # type: EventProcessor
1068
- ):
1069
- # type: (...) -> None
1041
+ def add_event_processor(self, func: EventProcessor) -> None:
1070
1042
  """Register a scope local event processor on the scope.
1071
1043
 
1072
1044
  :param func: This function behaves like `before_send.`
@@ -1082,10 +1054,9 @@ class Scope:
1082
1054
 
1083
1055
  def add_error_processor(
1084
1056
  self,
1085
- func, # type: ErrorProcessor
1086
- cls=None, # type: Optional[Type[BaseException]]
1087
- ):
1088
- # type: (...) -> None
1057
+ func: ErrorProcessor,
1058
+ cls: Optional[Type[BaseException]] = None,
1059
+ ) -> None:
1089
1060
  """Register a scope local error processor on the scope.
1090
1061
 
1091
1062
  :param func: A callback that works similar to an event processor but is invoked with the original exception info triple as second argument.
@@ -1096,8 +1067,7 @@ class Scope:
1096
1067
  cls_ = cls # For mypy.
1097
1068
  real_func = func
1098
1069
 
1099
- def func(event, exc_info):
1100
- # type: (Event, ExcInfo) -> Optional[Event]
1070
+ def wrapped_func(event: Event, exc_info: ExcInfo) -> Optional[Event]:
1101
1071
  try:
1102
1072
  is_inst = isinstance(exc_info[1], cls_)
1103
1073
  except Exception:
@@ -1106,15 +1076,17 @@ class Scope:
1106
1076
  return real_func(event, exc_info)
1107
1077
  return event
1108
1078
 
1109
- self._error_processors.append(func)
1079
+ self._error_processors.append(wrapped_func)
1110
1080
 
1111
- def _apply_level_to_event(self, event, hint, options):
1112
- # type: (Event, Hint, Optional[Dict[str, Any]]) -> None
1081
+ def _apply_level_to_event(
1082
+ self, event: Event, hint: Hint, options: Optional[Dict[str, Any]]
1083
+ ) -> None:
1113
1084
  if self._level is not None:
1114
1085
  event["level"] = self._level
1115
1086
 
1116
- def _apply_breadcrumbs_to_event(self, event, hint, options):
1117
- # type: (Event, Hint, Optional[Dict[str, Any]]) -> None
1087
+ def _apply_breadcrumbs_to_event(
1088
+ self, event: Event, hint: Hint, options: Optional[Dict[str, Any]]
1089
+ ) -> None:
1118
1090
  event.setdefault("breadcrumbs", {})
1119
1091
 
1120
1092
  # This check is just for mypy -
@@ -1136,38 +1108,47 @@ class Scope:
1136
1108
  logger.debug("Error when sorting breadcrumbs", exc_info=err)
1137
1109
  pass
1138
1110
 
1139
- def _apply_user_to_event(self, event, hint, options):
1140
- # type: (Event, Hint, Optional[Dict[str, Any]]) -> None
1111
+ def _apply_user_to_event(
1112
+ self, event: Event, hint: Hint, options: Optional[Dict[str, Any]]
1113
+ ) -> None:
1141
1114
  if event.get("user") is None and self._user is not None:
1142
1115
  event["user"] = self._user
1143
1116
 
1144
- def _apply_transaction_name_to_event(self, event, hint, options):
1145
- # type: (Event, Hint, Optional[Dict[str, Any]]) -> None
1117
+ def _apply_transaction_name_to_event(
1118
+ self, event: Event, hint: Hint, options: Optional[Dict[str, Any]]
1119
+ ) -> None:
1146
1120
  if event.get("transaction") is None and self._transaction is not None:
1147
1121
  event["transaction"] = self._transaction
1148
1122
 
1149
- def _apply_transaction_info_to_event(self, event, hint, options):
1150
- # type: (Event, Hint, Optional[Dict[str, Any]]) -> None
1123
+ def _apply_transaction_info_to_event(
1124
+ self, event: Event, hint: Hint, options: Optional[Dict[str, Any]]
1125
+ ) -> None:
1151
1126
  if event.get("transaction_info") is None and self._transaction_info is not None:
1152
1127
  event["transaction_info"] = self._transaction_info
1153
1128
 
1154
- def _apply_fingerprint_to_event(self, event, hint, options):
1155
- # type: (Event, Hint, Optional[Dict[str, Any]]) -> None
1129
+ def _apply_fingerprint_to_event(
1130
+ self, event: Event, hint: Hint, options: Optional[Dict[str, Any]]
1131
+ ) -> None:
1156
1132
  if event.get("fingerprint") is None and self._fingerprint is not None:
1157
1133
  event["fingerprint"] = self._fingerprint
1158
1134
 
1159
- def _apply_extra_to_event(self, event, hint, options):
1160
- # type: (Event, Hint, Optional[Dict[str, Any]]) -> None
1135
+ def _apply_extra_to_event(
1136
+ self, event: Event, hint: Hint, options: Optional[Dict[str, Any]]
1137
+ ) -> None:
1161
1138
  if self._extras:
1162
1139
  event.setdefault("extra", {}).update(self._extras)
1163
1140
 
1164
- def _apply_tags_to_event(self, event, hint, options):
1165
- # type: (Event, Hint, Optional[Dict[str, Any]]) -> None
1141
+ def _apply_tags_to_event(
1142
+ self, event: Event, hint: Hint, options: Optional[Dict[str, Any]]
1143
+ ) -> None:
1166
1144
  if self._tags:
1167
- event.setdefault("tags", {}).update(self._tags)
1145
+ event.setdefault("tags", {}).update(
1146
+ {k: safe_str(v) for k, v in self._tags.items()}
1147
+ )
1168
1148
 
1169
- def _apply_contexts_to_event(self, event, hint, options):
1170
- # type: (Event, Hint, Optional[Dict[str, Any]]) -> None
1149
+ def _apply_contexts_to_event(
1150
+ self, event: Event, hint: Hint, options: Optional[Dict[str, Any]]
1151
+ ) -> None:
1171
1152
  if self._contexts:
1172
1153
  event.setdefault("contexts", {}).update(self._contexts)
1173
1154
 
@@ -1176,7 +1157,8 @@ class Scope:
1176
1157
  # Add "trace" context
1177
1158
  if contexts.get("trace") is None:
1178
1159
  if (
1179
- has_tracing_enabled(options)
1160
+ options is not None
1161
+ and has_tracing_enabled(options)
1180
1162
  and self._span is not None
1181
1163
  and self._span.is_valid
1182
1164
  ):
@@ -1184,21 +1166,20 @@ class Scope:
1184
1166
  else:
1185
1167
  contexts["trace"] = self.get_trace_context()
1186
1168
 
1187
- def _apply_flags_to_event(self, event, hint, options):
1188
- # type: (Event, Hint, Optional[Dict[str, Any]]) -> None
1169
+ def _apply_flags_to_event(
1170
+ self, event: Event, hint: Hint, options: Optional[Dict[str, Any]]
1171
+ ) -> None:
1189
1172
  flags = self.flags.get()
1190
1173
  if len(flags) > 0:
1191
1174
  event.setdefault("contexts", {}).setdefault("flags", {}).update(
1192
1175
  {"values": flags}
1193
1176
  )
1194
1177
 
1195
- def _drop(self, cause, ty):
1196
- # type: (Any, str) -> Optional[Any]
1178
+ def _drop(self, cause: Any, ty: str) -> Optional[Any]:
1197
1179
  logger.info("%s (%s) dropped event", ty, cause)
1198
1180
  return None
1199
1181
 
1200
- def run_error_processors(self, event, hint):
1201
- # type: (Event, Hint) -> Optional[Event]
1182
+ def run_error_processors(self, event: Event, hint: Hint) -> Optional[Event]:
1202
1183
  """
1203
1184
  Runs the error processors on the event and returns the modified event.
1204
1185
  """
@@ -1219,8 +1200,7 @@ class Scope:
1219
1200
 
1220
1201
  return event
1221
1202
 
1222
- def run_event_processors(self, event, hint):
1223
- # type: (Event, Hint) -> Optional[Event]
1203
+ def run_event_processors(self, event: Event, hint: Hint) -> Optional[Event]:
1224
1204
  """
1225
1205
  Runs the event processors on the event and returns the modified event.
1226
1206
  """
@@ -1240,7 +1220,7 @@ class Scope:
1240
1220
  )
1241
1221
 
1242
1222
  for event_processor in event_processors:
1243
- new_event = event # type: Optional[Event]
1223
+ new_event: Optional[Event] = event
1244
1224
  with capture_internal_exceptions():
1245
1225
  new_event = event_processor(event, hint)
1246
1226
  if new_event is None:
@@ -1252,11 +1232,10 @@ class Scope:
1252
1232
  @_disable_capture
1253
1233
  def apply_to_event(
1254
1234
  self,
1255
- event, # type: Event
1256
- hint, # type: Hint
1257
- options=None, # type: Optional[Dict[str, Any]]
1258
- ):
1259
- # type: (...) -> Optional[Event]
1235
+ event: Event,
1236
+ hint: Hint,
1237
+ options: Optional[Dict[str, Any]] = None,
1238
+ ) -> Optional[Event]:
1260
1239
  """Applies the information contained on the scope to the given event."""
1261
1240
  ty = event.get("type")
1262
1241
  is_transaction = ty == "transaction"
@@ -1302,8 +1281,7 @@ class Scope:
1302
1281
 
1303
1282
  return event
1304
1283
 
1305
- def update_from_scope(self, scope):
1306
- # type: (Scope) -> None
1284
+ def update_from_scope(self, scope: Scope) -> None:
1307
1285
  """Update the scope with another scope's data."""
1308
1286
  if scope._level is not None:
1309
1287
  self._level = scope._level
@@ -1346,14 +1324,13 @@ class Scope:
1346
1324
 
1347
1325
  def update_from_kwargs(
1348
1326
  self,
1349
- user=None, # type: Optional[Any]
1350
- level=None, # type: Optional[LogLevelStr]
1351
- extras=None, # type: Optional[Dict[str, Any]]
1352
- contexts=None, # type: Optional[Dict[str, Dict[str, Any]]]
1353
- tags=None, # type: Optional[Dict[str, str]]
1354
- fingerprint=None, # type: Optional[List[str]]
1355
- ):
1356
- # type: (...) -> None
1327
+ user: Optional[Any] = None,
1328
+ level: Optional[LogLevelStr] = None,
1329
+ extras: Optional[Dict[str, Any]] = None,
1330
+ contexts: Optional[Dict[str, Dict[str, Any]]] = None,
1331
+ tags: Optional[Dict[str, str]] = None,
1332
+ fingerprint: Optional[List[str]] = None,
1333
+ ) -> None:
1357
1334
  """Update the scope's attributes."""
1358
1335
  if level is not None:
1359
1336
  self._level = level
@@ -1368,8 +1345,7 @@ class Scope:
1368
1345
  if fingerprint is not None:
1369
1346
  self._fingerprint = fingerprint
1370
1347
 
1371
- def __repr__(self):
1372
- # type: () -> str
1348
+ def __repr__(self) -> str:
1373
1349
  return "<%s id=%s name=%s type=%s>" % (
1374
1350
  self.__class__.__name__,
1375
1351
  hex(id(self)),
@@ -1378,8 +1354,7 @@ class Scope:
1378
1354
  )
1379
1355
 
1380
1356
  @property
1381
- def flags(self):
1382
- # type: () -> FlagBuffer
1357
+ def flags(self) -> FlagBuffer:
1383
1358
  if self._flags is None:
1384
1359
  max_flags = (
1385
1360
  self.get_client().options["_experiments"].get("max_flags")
@@ -1390,8 +1365,7 @@ class Scope:
1390
1365
 
1391
1366
 
1392
1367
  @contextmanager
1393
- def new_scope():
1394
- # type: () -> Generator[Scope, None, None]
1368
+ def new_scope() -> Generator[Scope, None, None]:
1395
1369
  """
1396
1370
  .. versionadded:: 2.0.0
1397
1371
 
@@ -1420,13 +1394,15 @@ def new_scope():
1420
1394
  yield new_scope
1421
1395
 
1422
1396
  finally:
1423
- # restore original scope
1424
- _current_scope.reset(token)
1397
+ try:
1398
+ # restore original scope
1399
+ _current_scope.reset(token)
1400
+ except LookupError:
1401
+ capture_internal_exception(sys.exc_info())
1425
1402
 
1426
1403
 
1427
1404
  @contextmanager
1428
- def use_scope(scope):
1429
- # type: (Scope) -> Generator[Scope, None, None]
1405
+ def use_scope(scope: Scope) -> Generator[Scope, None, None]:
1430
1406
  """
1431
1407
  .. versionadded:: 2.0.0
1432
1408
 
@@ -1455,13 +1431,15 @@ def use_scope(scope):
1455
1431
  yield scope
1456
1432
 
1457
1433
  finally:
1458
- # restore original scope
1459
- _current_scope.reset(token)
1434
+ try:
1435
+ # restore original scope
1436
+ _current_scope.reset(token)
1437
+ except LookupError:
1438
+ capture_internal_exception(sys.exc_info())
1460
1439
 
1461
1440
 
1462
1441
  @contextmanager
1463
- def isolation_scope():
1464
- # type: () -> Generator[Scope, None, None]
1442
+ def isolation_scope() -> Generator[Scope, None, None]:
1465
1443
  """
1466
1444
  .. versionadded:: 2.0.0
1467
1445
 
@@ -1497,13 +1475,19 @@ def isolation_scope():
1497
1475
 
1498
1476
  finally:
1499
1477
  # restore original scopes
1500
- _current_scope.reset(current_token)
1501
- _isolation_scope.reset(isolation_token)
1478
+ try:
1479
+ _current_scope.reset(current_token)
1480
+ except LookupError:
1481
+ capture_internal_exception(sys.exc_info())
1482
+
1483
+ try:
1484
+ _isolation_scope.reset(isolation_token)
1485
+ except LookupError:
1486
+ capture_internal_exception(sys.exc_info())
1502
1487
 
1503
1488
 
1504
1489
  @contextmanager
1505
- def use_isolation_scope(isolation_scope):
1506
- # type: (Scope) -> Generator[Scope, None, None]
1490
+ def use_isolation_scope(isolation_scope: Scope) -> Generator[Scope, None, None]:
1507
1491
  """
1508
1492
  .. versionadded:: 2.0.0
1509
1493
 
@@ -1537,18 +1521,21 @@ def use_isolation_scope(isolation_scope):
1537
1521
 
1538
1522
  finally:
1539
1523
  # restore original scopes
1540
- _current_scope.reset(current_token)
1541
- _isolation_scope.reset(isolation_token)
1524
+ try:
1525
+ _current_scope.reset(current_token)
1526
+ except LookupError:
1527
+ capture_internal_exception(sys.exc_info())
1528
+
1529
+ try:
1530
+ _isolation_scope.reset(isolation_token)
1531
+ except LookupError:
1532
+ capture_internal_exception(sys.exc_info())
1542
1533
 
1543
1534
 
1544
- def should_send_default_pii():
1545
- # type: () -> bool
1535
+ def should_send_default_pii() -> bool:
1546
1536
  """Shortcut for `Scope.get_client().should_send_default_pii()`."""
1547
1537
  return Scope.get_client().should_send_default_pii()
1548
1538
 
1549
1539
 
1550
1540
  # Circular imports
1551
1541
  from sentry_sdk.client import NonRecordingClient
1552
-
1553
- if TYPE_CHECKING:
1554
- import sentry_sdk.client