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