Skip to content

Commit d29ff87

Browse files
committed
ref: Add more type annotations
1 parent c480d55 commit d29ff87

File tree

6 files changed

+79
-16
lines changed

6 files changed

+79
-16
lines changed

mypy.ini

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ disallow_incomplete_defs = True
1010
; disallow_subclassing_any = True
1111
; disallow_untyped_calls = True
1212
disallow_untyped_decorators = True
13-
; disallow_untyped_defs = True
13+
disallow_untyped_defs = True
1414
no_implicit_optional = True
1515
strict_equality = True
1616
strict_optional = True
@@ -19,11 +19,25 @@ warn_redundant_casts = True
1919
; warn_unused_configs = True
2020
; warn_unused_ignores = True
2121

22+
23+
; Relaxations:
24+
25+
[mypy-sentry_sdk.tracing]
26+
disallow_untyped_defs = False
27+
28+
[mypy-sentry_sdk._compat]
29+
disallow_untyped_defs = False
30+
31+
[mypy-sentry_sdk.scope]
32+
disallow_untyped_defs = False
33+
2234
[mypy-sentry_sdk.integrations.*]
2335
disallow_any_generics = False
36+
disallow_untyped_defs = False
2437

2538
[mypy-sentry_sdk.utils]
2639
disallow_any_generics = False
40+
disallow_untyped_defs = False
2741

2842
[mypy-django.*]
2943
ignore_missing_imports = True

sentry_sdk/api.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@
1515

1616
from sentry_sdk.utils import Event, Hint, Breadcrumb, BreadcrumbHint
1717

18+
T = TypeVar("T")
1819
F = TypeVar("F", bound=Callable[..., Any])
1920
else:
2021

2122
def overload(x):
23+
# type: (T) -> T
2224
return x
2325

2426

@@ -91,7 +93,10 @@ def configure_scope(callback):
9193

9294

9395
@hubmethod # noqa
94-
def configure_scope(callback=None):
96+
def configure_scope(
97+
callback=None # type: Optional[Callable[[Scope], None]]
98+
):
99+
# type: (...) -> Optional[ContextManager[Scope]]
95100
hub = Hub.current
96101
if hub is not None:
97102
return hub.configure_scope(callback)
@@ -120,7 +125,10 @@ def push_scope(callback):
120125

121126

122127
@hubmethod # noqa
123-
def push_scope(callback=None):
128+
def push_scope(
129+
callback=None # type: Optional[Callable[[Scope], None]]
130+
):
131+
# type: (...) -> Optional[ContextManager[Scope]]
124132
hub = Hub.current
125133
if hub is not None:
126134
return hub.push_scope(callback)
@@ -138,6 +146,7 @@ def inner():
138146

139147
@hubmethod
140148
def flush(timeout=None, callback=None):
149+
# type: (Optional[float], Optional[Callable[[int, float], None]]) -> None
141150
hub = Hub.current
142151
if hub is not None:
143152
return hub.flush(timeout=timeout, callback=callback)

sentry_sdk/client.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ def __init__(self, *args, **kwargs):
9292

9393
@property
9494
def dsn(self):
95+
# type: () -> Optional[str]
9596
"""Returns the configured DSN as string."""
9697
return self.options["dsn"]
9798

@@ -259,7 +260,9 @@ def flush(self, timeout=None, callback=None):
259260
self.transport.flush(timeout=timeout, callback=callback)
260261

261262
def __enter__(self):
263+
# type: () -> Client
262264
return self
263265

264266
def __exit__(self, exc_type, exc_value, tb):
267+
# type: (Any, Any, Any) -> None
265268
self.close()

sentry_sdk/debug.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ def configure_logger():
3838
def configure_debug_hub():
3939
# type: () -> None
4040
def _get_debug_hub():
41+
# type: () -> Hub
4142
return Hub.current
4243

4344
utils._get_debug_hub = _get_debug_hub

sentry_sdk/hub.py

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,17 @@
2828
from typing import Callable
2929
from typing import Generator
3030
from typing import Type
31+
from typing import TypeVar
3132
from typing import overload
3233

3334
from sentry_sdk.integrations import Integration
3435
from sentry_sdk.utils import Event, Hint, Breadcrumb, BreadcrumbHint
36+
37+
T = TypeVar("T")
3538
else:
3639

3740
def overload(x):
41+
# type: (T) -> T
3842
return x
3943

4044

@@ -60,12 +64,15 @@ def __enter__(self):
6064
return self
6165

6266
def __exit__(self, exc_type, exc_value, tb):
67+
# type: (Any, Any, Any) -> None
6368
c = self._client
6469
if c is not None:
6570
c.close()
6671

6772

6873
def init(*args, **kwargs):
74+
# type: (*str, **Any) -> ContextManager[Any]
75+
# TODO: https://github.com/getsentry/sentry-python/issues/272
6976
"""Initializes the SDK and optionally integrations.
7077
7178
This takes the same arguments as the client constructor.
@@ -92,16 +99,19 @@ def current(self):
9299

93100
@property
94101
def main(self):
102+
# type: () -> Hub
95103
"""Returns the main instance of the hub."""
96104
return GLOBAL_HUB
97105

98106

99107
class _HubManager(object):
100108
def __init__(self, hub):
109+
# type: (Hub) -> None
101110
self._old = Hub.current
102111
_local.set(hub)
103112

104113
def __exit__(self, exc_type, exc_value, tb):
114+
# type: (Any, Any, Any) -> None
105115
_local.set(self._old)
106116

107117

@@ -119,6 +129,7 @@ def __enter__(self):
119129
return scope
120130

121131
def __exit__(self, exc_type, exc_value, tb):
132+
# type: (Any, Any, Any) -> None
122133
current_len = len(self._hub._stack)
123134
if current_len < self._original_len:
124135
logger.error(
@@ -200,6 +211,7 @@ def __exit__(
200211
_local.set(old)
201212

202213
def run(self, callback):
214+
# type: (Callable[[], T]) -> T
203215
"""Runs a callback in the context of the hub. Alternatively the
204216
with statement can be used on the hub directly.
205217
"""
@@ -260,6 +272,7 @@ def last_event_id(self):
260272
return self._last_event_id
261273

262274
def bind_client(self, new):
275+
# type: (Optional[Client]) -> None
263276
"""Binds a new client to the hub."""
264277
top = self._stack[-1]
265278
self._stack[-1] = (new, top[1])
@@ -361,16 +374,19 @@ def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
361374
scope._breadcrumbs.popleft()
362375

363376
@overload # noqa
364-
def push_scope(self):
365-
# type: () -> ContextManager[Scope]
377+
def push_scope(self, callback=None):
378+
# type: (Optional[None]) -> ContextManager[Scope]
366379
pass
367380

368381
@overload # noqa
369382
def push_scope(self, callback):
370383
# type: (Callable[[Scope], None]) -> None
371384
pass
372385

373-
def push_scope(self, callback=None): # noqa
386+
def push_scope( # noqa
387+
self, callback=None # type: Optional[Callable[[Scope], None]]
388+
):
389+
# type: (...) -> Optional[ContextManager[Scope]]
374390
"""Pushes a new layer on the scope stack. Returns a context manager
375391
that should be used to pop the scope again. Alternatively a callback
376392
can be provided that is executed in the context of the scope.
@@ -390,23 +406,28 @@ def push_scope(self, callback=None): # noqa
390406
scope = push_scope
391407

392408
def pop_scope_unsafe(self):
409+
# type: () -> Tuple[Optional[Client], Scope]
393410
"""Pops a scope layer from the stack. Try to use the context manager
394411
`push_scope()` instead."""
395412
rv = self._stack.pop()
396413
assert self._stack, "stack must have at least one layer"
397414
return rv
398415

399416
@overload # noqa
400-
def configure_scope(self):
401-
# type: () -> ContextManager[Scope]
417+
def configure_scope(self, callback=None):
418+
# type: (Optional[None]) -> ContextManager[Scope]
402419
pass
403420

404421
@overload # noqa
405422
def configure_scope(self, callback):
406423
# type: (Callable[[Scope], None]) -> None
407424
pass
408425

409-
def configure_scope(self, callback=None): # noqa
426+
def configure_scope( # noqa
427+
self, callback=None # type: Optional[Callable[[Scope], None]]
428+
): # noqa
429+
# type: (...) -> Optional[ContextManager[Scope]]
430+
410431
"""Reconfigures the scope."""
411432

412433
client, scope = self._stack[-1]
@@ -418,6 +439,7 @@ def configure_scope(self, callback=None): # noqa
418439

419440
@contextmanager
420441
def inner():
442+
# type: () -> Generator[Scope, None, None]
421443
if client is not None:
422444
yield scope
423445
else:

sentry_sdk/serializer.py

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@
1515
from typing import Dict
1616
from typing import List
1717
from typing import Optional
18+
from typing import Callable
19+
from typing import Union
20+
from typing import Generator
21+
22+
ReprProcessor = Callable[[Any, Dict[str, Any]], Union[NotImplemented, str]]
23+
Segment = Union[str, int]
1824

1925

2026
if PY2:
@@ -31,10 +37,11 @@
3137
CYCLE_MARKER = u"<cyclic>"
3238

3339

34-
global_repr_processors = []
40+
global_repr_processors = [] # type: List[ReprProcessor]
3541

3642

3743
def add_global_repr_processor(processor):
44+
# type: (ReprProcessor) -> None
3845
global_repr_processors.append(processor)
3946

4047

@@ -50,8 +57,8 @@ class MetaNode(object):
5057

5158
def __init__(self):
5259
# type: () -> None
53-
self._parent = None
54-
self._segment = None
60+
self._parent = None # type: Optional[MetaNode]
61+
self._segment = None # type: Optional[Segment]
5562
self._depth = 0 # type: int
5663
self._data = None # type: Optional[Dict[str, Any]]
5764
self._is_databag = None # type: Optional[bool]
@@ -79,6 +86,7 @@ def is_path(self, path):
7986
return cur._segment is None
8087

8188
def enter(self, segment):
89+
# type: (Segment) -> MetaNode
8290
rv = MetaNode()
8391
rv._parent = self
8492
rv._depth = self._depth + 1
@@ -93,7 +101,7 @@ def _create_annotations(self):
93101
self._data = {}
94102
if self._parent is not None:
95103
self._parent._create_annotations()
96-
self._parent._data[str(self._segment)] = self._data
104+
self._parent._data[str(self._segment)] = self._data # type: ignore
97105

98106
def annotate(self, **meta):
99107
# type: (Any) -> None
@@ -150,6 +158,7 @@ def __init__(self):
150158

151159
@contextlib.contextmanager
152160
def memoize(self, obj):
161+
# type: (Any) -> Generator[bool, None, None]
153162
if id(obj) in self._inner:
154163
yield True
155164
else:
@@ -167,6 +176,7 @@ def __init__(self):
167176

168177
@contextlib.contextmanager
169178
def enter(self, segment):
179+
# type: (Segment) -> Generator[None, None, None]
170180
old_node = self.meta_node
171181
self.meta_node = self.meta_node.enter(segment)
172182

@@ -176,25 +186,29 @@ def enter(self, segment):
176186
self.meta_node = old_node
177187

178188
def serialize_event(self, obj):
189+
# type: (Any) -> Dict[str, Any]
179190
rv = self._serialize_node(obj)
180191
if self.meta_node._data is not None:
181192
rv["_meta"] = self.meta_node._data
182193
return rv
183194

184-
def _serialize_node(self, obj, **kwargs):
195+
def _serialize_node(self, obj, max_depth=None, max_breadth=None):
196+
# type: (Any, Optional[int], Optional[int]) -> Any
185197
with capture_internal_exceptions():
186198
with self.memo.memoize(obj) as result:
187199
if result:
188200
return CYCLE_MARKER
189201

190-
return self._serialize_node_impl(obj, **kwargs)
202+
return self._serialize_node_impl(
203+
obj, max_depth=max_depth, max_breadth=max_breadth
204+
)
191205

192206
if self.meta_node.is_databag():
193207
return u"<failed to serialize, use init(debug=True) to see error logs>"
194208

195209
return None
196210

197-
def _serialize_node_impl(self, obj, max_depth=None, max_breadth=None):
211+
def _serialize_node_impl(self, obj, max_depth, max_breadth):
198212
# type: (Any, Optional[int], Optional[int]) -> Any
199213
if max_depth is None and max_breadth is None and self.meta_node.is_databag():
200214
max_depth = self.meta_node._depth + MAX_DATABAG_DEPTH

0 commit comments

Comments
 (0)