Skip to content

Commit 1272d3c

Browse files
Replace type hints with modern type annotations
1 parent 0f95a68 commit 1272d3c

File tree

1 file changed

+40
-47
lines changed

1 file changed

+40
-47
lines changed

ddtrace/profiling/collector/_lock.py

Lines changed: 40 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,12 @@
66
import sys
77
import time
88
import types
9-
import typing
9+
from typing import Any
10+
from typing import Callable
11+
from typing import Dict
12+
from typing import Optional
13+
from typing import Tuple
14+
from typing import Type
1015

1116
import wrapt
1217

@@ -19,8 +24,7 @@
1924
from ddtrace.trace import Tracer
2025

2126

22-
def _current_thread():
23-
# type: (...) -> typing.Tuple[int, str]
27+
def _current_thread() -> Tuple[int, str]:
2428
thread_id = _thread.get_ident()
2529
return thread_id, _threading.get_thread_name(thread_id)
2630

@@ -42,8 +46,8 @@ def _current_thread():
4246
class _ProfiledLock(wrapt.ObjectProxy):
4347
def __init__(
4448
self,
45-
wrapped: typing.Any,
46-
tracer: typing.Optional[Tracer],
49+
wrapped: Any,
50+
tracer: Optional[Tracer],
4751
max_nframes: int,
4852
capture_sampler: collector.CaptureSampler,
4953
endpoint_collection_enabled: bool,
@@ -56,15 +60,15 @@ def __init__(
5660
frame = sys._getframe(2 if WRAPT_C_EXT else 3)
5761
code = frame.f_code
5862
self._self_init_loc = "%s:%d" % (os.path.basename(code.co_filename), frame.f_lineno)
59-
self._self_name: typing.Optional[str] = None
63+
self._self_name: Optional[str] = None
6064

61-
def __aenter__(self, *args, **kwargs):
65+
def __aenter__(self, *args: Any, **kwargs: Any) -> Any:
6266
return self._acquire(self.__wrapped__.__aenter__, *args, **kwargs)
6367

64-
def __aexit__(self, *args, **kwargs):
68+
def __aexit__(self, *args: Any, **kwargs: Any) -> Any:
6569
return self._release(self.__wrapped__.__aexit__, *args, **kwargs)
6670

67-
def _acquire(self, inner_func, *args, **kwargs):
71+
def _acquire(self, inner_func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
6872
if not self._self_capture_sampler.capture():
6973
return inner_func(*args, **kwargs)
7074

@@ -106,12 +110,10 @@ def _acquire(self, inner_func, *args, **kwargs):
106110
except Exception:
107111
pass # nosec
108112

109-
def acquire(self, *args, **kwargs):
113+
def acquire(self, *args: Any, **kwargs: Any) -> Any:
110114
return self._acquire(self.__wrapped__.acquire, *args, **kwargs)
111115

112-
def _release(self, inner_func, *args, **kwargs):
113-
# type (typing.Any, typing.Any) -> None
114-
116+
def _release(self, inner_func: Any, *args: Any, **kwargs: Any) -> None:
115117
# The underlying threading.Lock class is implemented using C code, and
116118
# it doesn't have the __dict__ attribute. So we can't do
117119
# self.__dict__.pop("_self_acquired_at", None) to remove the attribute.
@@ -162,18 +164,18 @@ def _release(self, inner_func, *args, **kwargs):
162164
handle.push_frame(frame.function_name, frame.file_name, 0, frame.lineno)
163165
handle.flush_sample()
164166

165-
def release(self, *args, **kwargs):
167+
def release(self, *args: Any, **kwargs: Any) -> Any:
166168
return self._release(self.__wrapped__.release, *args, **kwargs)
167169

168170
acquire_lock = acquire
169171

170-
def __enter__(self, *args, **kwargs):
172+
def __enter__(self, *args: Any, **kwargs: Any) -> Any:
171173
return self._acquire(self.__wrapped__.__enter__, *args, **kwargs)
172174

173-
def __exit__(self, *args, **kwargs):
175+
def __exit__(self, *args: Any, **kwargs: Any) -> None:
174176
self._release(self.__wrapped__.__exit__, *args, **kwargs)
175177

176-
def _find_self_name(self, var_dict: typing.Dict):
178+
def _find_self_name(self, var_dict: Dict[str, Any]) -> Optional[str]:
177179
for name, value in var_dict.items():
178180
if name.startswith("__") or isinstance(value, types.ModuleType):
179181
continue
@@ -188,7 +190,7 @@ def _find_self_name(self, var_dict: typing.Dict):
188190

189191
# Get lock acquire/release call location and variable name the lock is assigned to
190192
# This function propagates ValueError if the frame depth is <= 3.
191-
def _maybe_update_self_name(self):
193+
def _maybe_update_self_name(self) -> None:
192194
if self._self_name is not None:
193195
return
194196
# We expect the call stack to be like this:
@@ -223,7 +225,7 @@ class FunctionWrapper(wrapt.FunctionWrapper):
223225
# Override the __get__ method: whatever happens, _allocate_lock is always considered by Python like a "static"
224226
# method, even when used as a class attribute. Python never tried to "bind" it to a method, because it sees it is a
225227
# builtin function. Override default wrapt behavior here that tries to detect bound method.
226-
def __get__(self, instance, owner=None):
228+
def __get__(self, instance: Any, owner: Optional[Type] = None) -> "FunctionWrapper":
227229
return self
228230

229231

@@ -232,51 +234,43 @@ class LockCollector(collector.CaptureSamplerCollector):
232234

233235
def __init__(
234236
self,
235-
nframes=config.max_frames,
236-
endpoint_collection_enabled=config.endpoint_collection,
237-
tracer=None,
238-
*args,
239-
**kwargs,
240-
):
237+
nframes: int = config.max_frames,
238+
endpoint_collection_enabled: bool = config.endpoint_collection,
239+
tracer: Optional[Tracer] = None,
240+
*args: Any,
241+
**kwargs: Any,
242+
) -> None:
241243
super().__init__(*args, **kwargs)
242-
self.nframes = nframes
243-
self.endpoint_collection_enabled = endpoint_collection_enabled
244-
self.tracer = tracer
245-
self._original = None
244+
self.nframes: int = nframes
245+
self.endpoint_collection_enabled: bool = endpoint_collection_enabled
246+
self.tracer: Optional[Tracer] = tracer
247+
self._original: Optional[Any] = None
246248

247249
@abc.abstractmethod
248-
def _get_patch_target(self):
249-
# type: (...) -> typing.Any
250-
pass
250+
def _get_patch_target(self) -> Callable[..., Any]:
251+
...
251252

252253
@abc.abstractmethod
253-
def _set_patch_target(
254-
self,
255-
value, # type: typing.Any
256-
):
257-
# type: (...) -> None
258-
pass
254+
def _set_patch_target(self, value: Any) -> None:
255+
...
259256

260-
def _start_service(self):
261-
# type: (...) -> None
257+
def _start_service(self) -> None:
262258
"""Start collecting lock usage."""
263259
self.patch()
264260
super(LockCollector, self)._start_service() # type: ignore[safe-super]
265261

266-
def _stop_service(self):
267-
# type: (...) -> None
262+
def _stop_service(self) -> None:
268263
"""Stop collecting lock usage."""
269264
super(LockCollector, self)._stop_service() # type: ignore[safe-super]
270265
self.unpatch()
271266

272-
def patch(self):
273-
# type: (...) -> None
267+
def patch(self) -> None:
274268
"""Patch the module for tracking lock allocation."""
275269
# We only patch the lock from the `threading` module.
276270
# Nobody should use locks from `_thread`; if they do so, then it's deliberate and we don't profile.
277271
self._original = self._get_patch_target()
278272

279-
def _allocate_lock(wrapped, instance, args, kwargs):
273+
def _allocate_lock(wrapped: Any, instance: Any, args: Any, kwargs: Any) -> _ProfiledLock:
280274
lock = wrapped(*args, **kwargs)
281275
return self.PROFILED_LOCK_CLASS(
282276
lock,
@@ -288,7 +282,6 @@ def _allocate_lock(wrapped, instance, args, kwargs):
288282

289283
self._set_patch_target(FunctionWrapper(self._original, _allocate_lock))
290284

291-
def unpatch(self):
292-
# type: (...) -> None
285+
def unpatch(self) -> None:
293286
"""Unpatch the threading module for tracking lock allocation."""
294287
self._set_patch_target(self._original)

0 commit comments

Comments
 (0)