Skip to content

Commit

Permalink
chore: Annotate semaphore.py
Browse files Browse the repository at this point in the history
Related to celery#1511
  • Loading branch information
sondrelg committed Apr 8, 2022
1 parent 54638f2 commit e1ed5ca
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions kombu/asynchronous/semaphore.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

__all__ = ('DummyLock', 'LaxBoundedSemaphore')

from typing import Any, Callable


class LaxBoundedSemaphore:
"""Asynchronous Bounded Semaphore.
Expand All @@ -28,13 +30,18 @@ class LaxBoundedSemaphore:
HELLO 3
"""

def __init__(self, value):
def __init__(self, value: int) -> None:
self.initial_value = self.value = value
self._waiting = deque()
self._add_waiter = self._waiting.append
self._pop_waiter = self._waiting.popleft

def acquire(self, callback, *partial_args, **partial_kwargs):
def acquire(
self,
callback: Callable,
*partial_args: Any,
**partial_kwargs: Any
) -> bool:
"""Acquire semaphore.
This will immediately apply ``callback`` if
Expand All @@ -54,7 +61,7 @@ def acquire(self, callback, *partial_args, **partial_kwargs):
callback(*partial_args, **partial_kwargs)
return True

def release(self):
def release(self) -> None:
"""Release semaphore.
Note:
Expand All @@ -68,23 +75,23 @@ def release(self):
else:
waiter(*args, **kwargs)

def grow(self, n=1):
def grow(self, n: int = 1) -> None:
"""Change the size of the semaphore to accept more users."""
self.initial_value += n
self.value += n
[self.release() for _ in range(n)]

def shrink(self, n=1):
def shrink(self, n: int = 1) -> None:
"""Change the size of the semaphore to accept less users."""
self.initial_value = max(self.initial_value - n, 0)
self.value = max(self.value - n, 0)

def clear(self):
def clear(self) -> None:
"""Reset the semaphore, which also wipes out any waiting callbacks."""
self._waiting.clear()
self.value = self.initial_value

def __repr__(self):
def __repr__(self) -> str:
return '<{} at {:#x} value:{} waiting:{}>'.format(
self.__class__.__name__, id(self), self.value, len(self._waiting),
)
Expand All @@ -93,8 +100,8 @@ def __repr__(self):
class DummyLock:
"""Pretending to be a lock."""

def __enter__(self):
def __enter__(self) -> 'DummyLock':
return self

def __exit__(self, *exc_info):
def __exit__(self, *exc_info: Any) -> None:
pass

0 comments on commit e1ed5ca

Please sign in to comment.