Skip to content

Commit f6d64a5

Browse files
committed
Migrate typing for core files
1 parent 43348e9 commit f6d64a5

28 files changed

+1283
-1711
lines changed

docs/conf.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import opentelemetry.sdk.metrics._internal # noqa: F401
1818

1919
typing.TYPE_CHECKING = True
20+
import sentry_sdk
2021

2122
#
2223
# Configuration file for the Sphinx documentation builder.

sentry_sdk/_compat.py

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,25 @@
1+
from __future__ import annotations
12
import sys
2-
33
from typing import TYPE_CHECKING
44

55
if TYPE_CHECKING:
66
from typing import Any
7-
from typing import TypeVar
8-
9-
T = TypeVar("T")
107

118

129
PY38 = sys.version_info[0] == 3 and sys.version_info[1] >= 8
1310
PY310 = sys.version_info[0] == 3 and sys.version_info[1] >= 10
1411
PY311 = sys.version_info[0] == 3 and sys.version_info[1] >= 11
1512

1613

17-
def with_metaclass(meta, *bases):
18-
# type: (Any, *Any) -> Any
14+
def with_metaclass(meta: Any, *bases: Any) -> Any:
1915
class MetaClass(type):
20-
def __new__(metacls, name, this_bases, d):
21-
# type: (Any, Any, Any, Any) -> Any
16+
def __new__(metacls: Any, name: Any, this_bases: Any, d: Any) -> Any:
2217
return meta(name, bases, d)
2318

2419
return type.__new__(MetaClass, "temporary_class", (), {})
2520

2621

27-
def check_uwsgi_thread_support():
28-
# type: () -> bool
22+
def check_uwsgi_thread_support() -> bool:
2923
# We check two things here:
3024
#
3125
# 1. uWSGI doesn't run in threaded mode by default -- issue a warning if
@@ -45,8 +39,7 @@ def check_uwsgi_thread_support():
4539

4640
from sentry_sdk.consts import FALSE_VALUES
4741

48-
def enabled(option):
49-
# type: (str) -> bool
42+
def enabled(option: str) -> bool:
5043
value = opt.get(option, False)
5144
if isinstance(value, bool):
5245
return value

sentry_sdk/_init_implementation.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
1+
from __future__ import annotations
2+
13
from typing import TYPE_CHECKING
24

5+
if TYPE_CHECKING:
6+
from typing import Optional, Any
7+
38
import sentry_sdk
49
from sentry_sdk.consts import ClientConstructor
510
from sentry_sdk.opentelemetry.scope import setup_scope_context_management
611

7-
if TYPE_CHECKING:
8-
from typing import Any, Optional
9-
1012

11-
def _check_python_deprecations():
12-
# type: () -> None
13+
def _check_python_deprecations() -> None:
1314
# Since we're likely to deprecate Python versions in the future, I'm keeping
1415
# this handy function around. Use this to detect the Python version used and
1516
# to output logger.warning()s if it's deprecated.
1617
pass
1718

1819

19-
def _init(*args, **kwargs):
20-
# type: (*Optional[str], **Any) -> None
20+
def _init(*args: Optional[str], **kwargs: Any) -> None:
2121
"""Initializes the SDK and optionally integrations.
2222
2323
This takes the same arguments as the client constructor.

sentry_sdk/_log_batcher.py

Lines changed: 17 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,35 @@
1+
from __future__ import annotations
12
import os
23
import random
34
import threading
45
from datetime import datetime, timezone
5-
from typing import Optional, List, Callable, TYPE_CHECKING, Any
66

77
from sentry_sdk.utils import format_timestamp, safe_repr
88
from sentry_sdk.envelope import Envelope, Item, PayloadRef
99

10+
from typing import TYPE_CHECKING
11+
1012
if TYPE_CHECKING:
1113
from sentry_sdk._types import Log
14+
from typing import Optional, List, Callable, Any
1215

1316

1417
class LogBatcher:
1518
MAX_LOGS_BEFORE_FLUSH = 100
1619
FLUSH_WAIT_TIME = 5.0
1720

18-
def __init__(
19-
self,
20-
capture_func, # type: Callable[[Envelope], None]
21-
):
22-
# type: (...) -> None
23-
self._log_buffer = [] # type: List[Log]
21+
def __init__(self, capture_func: Callable[[Envelope], None]) -> None:
22+
self._log_buffer: List[Log] = []
2423
self._capture_func = capture_func
2524
self._running = True
2625
self._lock = threading.Lock()
2726

28-
self._flush_event = threading.Event() # type: threading.Event
27+
self._flush_event: threading.Event = threading.Event()
2928

30-
self._flusher = None # type: Optional[threading.Thread]
31-
self._flusher_pid = None # type: Optional[int]
29+
self._flusher: Optional[threading.Thread] = None
30+
self._flusher_pid: Optional[int] = None
3231

33-
def _ensure_thread(self):
34-
# type: (...) -> bool
32+
def _ensure_thread(self) -> bool:
3533
"""For forking processes we might need to restart this thread.
3634
This ensures that our process actually has that thread running.
3735
"""
@@ -63,18 +61,13 @@ def _ensure_thread(self):
6361

6462
return True
6563

66-
def _flush_loop(self):
67-
# type: (...) -> None
64+
def _flush_loop(self) -> None:
6865
while self._running:
6966
self._flush_event.wait(self.FLUSH_WAIT_TIME + random.random())
7067
self._flush_event.clear()
7168
self._flush()
7269

73-
def add(
74-
self,
75-
log, # type: Log
76-
):
77-
# type: (...) -> None
70+
def add(self, log: Log) -> None:
7871
if not self._ensure_thread() or self._flusher is None:
7972
return None
8073

@@ -83,24 +76,20 @@ def add(
8376
if len(self._log_buffer) >= self.MAX_LOGS_BEFORE_FLUSH:
8477
self._flush_event.set()
8578

86-
def kill(self):
87-
# type: (...) -> None
79+
def kill(self) -> None:
8880
if self._flusher is None:
8981
return
9082

9183
self._running = False
9284
self._flush_event.set()
9385
self._flusher = None
9486

95-
def flush(self):
96-
# type: (...) -> None
87+
def flush(self) -> None:
9788
self._flush()
9889

9990
@staticmethod
100-
def _log_to_transport_format(log):
101-
# type: (Log) -> Any
102-
def format_attribute(val):
103-
# type: (int | float | str | bool) -> Any
91+
def _log_to_transport_format(log: Log) -> Any:
92+
def format_attribute(val: int | float | str | bool) -> Any:
10493
if isinstance(val, bool):
10594
return {"value": val, "type": "boolean"}
10695
if isinstance(val, int):
@@ -128,8 +117,7 @@ def format_attribute(val):
128117

129118
return res
130119

131-
def _flush(self):
132-
# type: (...) -> Optional[Envelope]
120+
def _flush(self) -> Optional[Envelope]:
133121

134122
envelope = Envelope(
135123
headers={"sent_at": format_timestamp(datetime.now(timezone.utc))}

sentry_sdk/_lru_cache.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
from typing import TYPE_CHECKING
24

35
if TYPE_CHECKING:
@@ -8,17 +10,15 @@
810

911

1012
class LRUCache:
11-
def __init__(self, max_size):
12-
# type: (int) -> None
13+
def __init__(self, max_size: int) -> None:
1314
if max_size <= 0:
1415
raise AssertionError(f"invalid max_size: {max_size}")
1516
self.max_size = max_size
16-
self._data = {} # type: dict[Any, Any]
17+
self._data: dict[Any, Any] = {}
1718
self.hits = self.misses = 0
1819
self.full = False
1920

20-
def set(self, key, value):
21-
# type: (Any, Any) -> None
21+
def set(self, key: Any, value: Any) -> None:
2222
current = self._data.pop(key, _SENTINEL)
2323
if current is not _SENTINEL:
2424
self._data[key] = value
@@ -29,8 +29,7 @@ def set(self, key, value):
2929
self._data[key] = value
3030
self.full = len(self._data) >= self.max_size
3131

32-
def get(self, key, default=None):
33-
# type: (Any, Any) -> Any
32+
def get(self, key: Any, default: Any = None) -> Any:
3433
try:
3534
ret = self._data.pop(key)
3635
except KeyError:
@@ -42,6 +41,5 @@ def get(self, key, default=None):
4241

4342
return ret
4443

45-
def get_all(self):
46-
# type: () -> list[tuple[Any, Any]]
44+
def get_all(self) -> list[tuple[Any, Any]]:
4745
return list(self._data.items())

sentry_sdk/_queue.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,8 @@
7676
from collections import deque
7777
from time import time
7878

79-
from typing import TYPE_CHECKING
79+
from typing import Any
8080

81-
if TYPE_CHECKING:
82-
from typing import Any
8381

8482
__all__ = ["EmptyError", "FullError", "Queue"]
8583

@@ -275,7 +273,7 @@ def get_nowait(self):
275273

276274
# Initialize the queue representation
277275
def _init(self, maxsize):
278-
self.queue = deque() # type: Any
276+
self.queue: Any = deque()
279277

280278
def _qsize(self):
281279
return len(self.queue)

sentry_sdk/_types.py

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
from typing import TYPE_CHECKING, TypeVar, Union
24

35

@@ -18,32 +20,27 @@ class AnnotatedValue:
1820

1921
__slots__ = ("value", "metadata")
2022

21-
def __init__(self, value, metadata):
22-
# type: (Optional[Any], Dict[str, Any]) -> None
23+
def __init__(self, value: Optional[Any], metadata: Dict[str, Any]) -> None:
2324
self.value = value
2425
self.metadata = metadata
2526

26-
def __eq__(self, other):
27-
# type: (Any) -> bool
27+
def __eq__(self, other: Any) -> bool:
2828
if not isinstance(other, AnnotatedValue):
2929
return False
3030

3131
return self.value == other.value and self.metadata == other.metadata
3232

33-
def __str__(self):
34-
# type: (AnnotatedValue) -> str
33+
def __str__(self) -> str:
3534
return str({"value": str(self.value), "metadata": str(self.metadata)})
3635

37-
def __len__(self):
38-
# type: (AnnotatedValue) -> int
36+
def __len__(self) -> int:
3937
if self.value is not None:
4038
return len(self.value)
4139
else:
4240
return 0
4341

4442
@classmethod
45-
def removed_because_raw_data(cls):
46-
# type: () -> AnnotatedValue
43+
def removed_because_raw_data(cls) -> AnnotatedValue:
4744
"""The value was removed because it could not be parsed. This is done for request body values that are not json nor a form."""
4845
return AnnotatedValue(
4946
value="",
@@ -58,8 +55,7 @@ def removed_because_raw_data(cls):
5855
)
5956

6057
@classmethod
61-
def removed_because_over_size_limit(cls, value=""):
62-
# type: (Any) -> AnnotatedValue
58+
def removed_because_over_size_limit(cls, value: Any = "") -> AnnotatedValue:
6359
"""
6460
The actual value was removed because the size of the field exceeded the configured maximum size,
6561
for example specified with the max_request_body_size sdk option.
@@ -77,8 +73,7 @@ def removed_because_over_size_limit(cls, value=""):
7773
)
7874

7975
@classmethod
80-
def substituted_because_contains_sensitive_data(cls):
81-
# type: () -> AnnotatedValue
76+
def substituted_because_contains_sensitive_data(cls) -> AnnotatedValue:
8277
"""The actual value was removed because it contained sensitive information."""
8378
return AnnotatedValue(
8479
value=SENSITIVE_DATA_SUBSTITUTE,

sentry_sdk/_werkzeug.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,12 @@
3232
SUCH DAMAGE.
3333
"""
3434

35+
from __future__ import annotations
36+
3537
from typing import TYPE_CHECKING
3638

3739
if TYPE_CHECKING:
38-
from typing import Dict
39-
from typing import Iterator
40-
from typing import Tuple
40+
from typing import Dict, Iterator, Tuple
4141

4242

4343
#
@@ -47,8 +47,7 @@
4747
# We need this function because Django does not give us a "pure" http header
4848
# dict. So we might as well use it for all WSGI integrations.
4949
#
50-
def _get_headers(environ):
51-
# type: (Dict[str, str]) -> Iterator[Tuple[str, str]]
50+
def _get_headers(environ: Dict[str, str]) -> Iterator[Tuple[str, str]]:
5251
"""
5352
Returns only proper HTTP headers.
5453
"""
@@ -67,8 +66,7 @@ def _get_headers(environ):
6766
# `get_host` comes from `werkzeug.wsgi.get_host`
6867
# https://github.com/pallets/werkzeug/blob/1.0.1/src/werkzeug/wsgi.py#L145
6968
#
70-
def get_host(environ, use_x_forwarded_for=False):
71-
# type: (Dict[str, str], bool) -> str
69+
def get_host(environ: Dict[str, str], use_x_forwarded_for: bool = False) -> str:
7270
"""
7371
Return the host for the given WSGI environment.
7472
"""

0 commit comments

Comments
 (0)