Skip to content
Snippets Groups Projects
Commit 8e71a932 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

minor refactor

parent 5dbf3f73
No related branches found
No related tags found
No related merge requests found
...@@ -80,8 +80,8 @@ class CallableGroup(tp.Generic[T]): ...@@ -80,8 +80,8 @@ class CallableGroup(tp.Generic[T]):
class CallNoOftenThan: class CallNoOftenThan:
""" """
A class that will ensure that calls to given callable are made no sooner A class that will ensure that calls to given callable are made no more often
than after some interval. than some interval.
:param interval: interval in seconds :param interval: interval in seconds
:param callable_: callable to call :param callable_: callable to call
......
...@@ -13,6 +13,8 @@ class IDAllocator(Monitor): ...@@ -13,6 +13,8 @@ class IDAllocator(Monitor):
:param start_at: the lowest integer that the allocator will return :param start_at: the lowest integer that the allocator will return
""" """
__slots__ = ('start_at', 'ints_allocated', 'free_ints', 'bound')
def __init__(self, start_at: int = 0): def __init__(self, start_at: int = 0):
super().__init__() super().__init__()
self.start_at = start_at self.start_at = start_at
......
...@@ -67,7 +67,7 @@ class LockedDataset: ...@@ -67,7 +67,7 @@ class LockedDataset:
if inspect.ismethod(super(LockedDataset, self).__getattribute__(name)): if inspect.ismethod(super(LockedDataset, self).__getattribute__(name)):
return super(LockedDataset, self).__getattribute__(name) return super(LockedDataset, self).__getattribute__(name)
if not get_internal(self).locked: if not _get_internal(self).locked:
raise ResourceNotLocked('No lock held on this object for a read operation') raise ResourceNotLocked('No lock held on this object for a read operation')
return super(LockedDataset, self).__getattribute__(name) return super(LockedDataset, self).__getattribute__(name)
...@@ -75,27 +75,27 @@ class LockedDataset: ...@@ -75,27 +75,27 @@ class LockedDataset:
def __setattr__(self, key, value): def __setattr__(self, key, value):
if key == '_LockedDataset__internal': if key == '_LockedDataset__internal':
return super(LockedDataset, self).__setattr__(key, value) return super(LockedDataset, self).__setattr__(key, value)
if not get_internal(self).locked: if not _get_internal(self).locked:
raise ResourceNotLocked('No lock held on this object for a write operation') raise ResourceNotLocked('No lock held on this object for a write operation')
return super(LockedDataset, self).__setattr__(key, value) return super(LockedDataset, self).__setattr__(key, value)
def __call__(self, blocking=True, timeout=-1): def __call__(self, blocking=True, timeout=-1):
get_internal(self).args = blocking, timeout _get_internal(self).args = blocking, timeout
return self return self
def __enter__(self): def __enter__(self):
args = get_internal(self).args args = _get_internal(self).args
if not get_internal(self).lock.acquire(*args): if not _get_internal(self).lock.acquire(*args):
raise WouldWaitMore('Resource is still locked') raise WouldWaitMore('Resource is still locked')
get_internal(self).locked = True _get_internal(self).locked = True
return self return self
def __exit__(self, exc_type, exc_val, exc_tb): def __exit__(self, exc_type, exc_val, exc_tb):
get_internal(self).lock.release() _get_internal(self).lock.release()
get_internal(self).locked = False _get_internal(self).locked = False
return False return False
def get_internal(self): def _get_internal(self):
return super(LockedDataset, self).__getattribute__('_LockedDataset__internal') return super(LockedDataset, self).__getattribute__('_LockedDataset__internal')
...@@ -79,9 +79,11 @@ class DictDeleter: ...@@ -79,9 +79,11 @@ class DictDeleter:
del self.dict_to_process[key] del self.dict_to_process[key]
return False return False
DIR_FORWARD = 0 DIR_FORWARD = 0
DIR_BACKWARD = 1 DIR_BACKWARD = 1
class ListDeleter(tp.Generic[T]): class ListDeleter(tp.Generic[T]):
""" """
Having problems deleting entries from your list while iterating on them? No problem. Just swap Having problems deleting entries from your list while iterating on them? No problem. Just swap
......
...@@ -11,7 +11,7 @@ T, U = tp.TypeVar('T'), tp.TypeVar('U') ...@@ -11,7 +11,7 @@ T, U = tp.TypeVar('T'), tp.TypeVar('U')
IteratorOrIterable = tp.Union[tp.Iterator[T], tp.Iterable[T]] IteratorOrIterable = tp.Union[tp.Iterator[T], tp.Iterable[T]]
def walk(obj: T, child_getter: tp.Callable[[T], tp.List[T]] = list, def walk(obj: T, child_getter: tp.Callable[[T], tp.Optional[tp.List[T]]] = list,
deep_first: bool = True, deep_first: bool = True,
leafs_only: bool = False) -> tp.Iterator[T]: leafs_only: bool = False) -> tp.Iterator[T]:
""" """
......
...@@ -201,11 +201,10 @@ class ReprableMixin: ...@@ -201,11 +201,10 @@ class ReprableMixin:
def __repr__(self): def __repr__(self):
fragments = [] fragments = []
if hasattr(self, '_REPR_FULL_CLASSNAME'): if getattr(self, '_REPR_FULL_CLASSNAME', False):
if self._REPR_FULL_CLASSNAME: fragments = ['%s%s' % ((self.__class__.__module__ + '.')
fragments = ['%s%s' % ((self.__class__.__module__ + '.') if self.__class__.__module__ != 'builtins' else '',
if self.__class__.__module__ != 'builtins' else '', self.__class__.__qualname__)]
self.__class__.__qualname__)]
if not fragments: if not fragments:
fragments = [self.__class__.__name__] fragments = [self.__class__.__name__]
fragments.append('(') fragments.append('(')
......
from .dump_to_file import * from .dump_to_file import DumpToFileHandler, AsStream
from .exception_handlers import * from .exception_handlers import BaseExceptionHandler, FunctionExceptionHandler, \
from .global_eh import * exception_handler, NORMAL_PRIORITY, ALWAYS_FIRST, ALWAYS_LAST
from .global_eh import GlobalExcepthook
from .memerrhandler import MemoryErrorExceptionHandler from .memerrhandler import MemoryErrorExceptionHandler
__all__ = [ __all__ = [
......
...@@ -8,9 +8,6 @@ from satella.coding import silence_excs ...@@ -8,9 +8,6 @@ from satella.coding import silence_excs
from satella.instrumentation import Traceback from satella.instrumentation import Traceback
from .exception_handlers import BaseExceptionHandler from .exception_handlers import BaseExceptionHandler
__all__ = [
'DumpToFileHandler'
]
AsStreamTypeAccept = tp.Union[str, tp.IO, None] AsStreamTypeAccept = tp.Union[str, tp.IO, None]
AsStreamTypeAcceptHR = tp.Union[str, tp.TextIO] AsStreamTypeAcceptHR = tp.Union[str, tp.TextIO]
......
...@@ -68,7 +68,7 @@ class FunctionExceptionHandler(BaseExceptionHandler): ...@@ -68,7 +68,7 @@ class FunctionExceptionHandler(BaseExceptionHandler):
__slots__ = ('fun',) __slots__ = ('fun',)
def __init__(self, fun: ExceptionHandlerCallable, priority: int = NORMAL_PRIORITY): def __init__(self, fun: ExceptionHandlerCallable, priority: int = NORMAL_PRIORITY):
super(FunctionExceptionHandler, self).__init__(priority) super().__init__(priority)
self.fun = fun self.fun = fun
def handle_exception(self, type_, value, traceback): def handle_exception(self, type_, value, traceback):
......
...@@ -7,7 +7,7 @@ from .exceptions import ProcessFailed ...@@ -7,7 +7,7 @@ from .exceptions import ProcessFailed
__all__ = ['call_and_return_stdout'] __all__ = ['call_and_return_stdout']
def read_nowait(process: subprocess.Popen, output_list: tp.List[str]) -> None: def _read_nowait(process: subprocess.Popen, output_list: tp.List[str]) -> None:
""" """
To be launched as a daemon thread. This reads stdout and appends it's entries to a list. To be launched as a daemon thread. This reads stdout and appends it's entries to a list.
This should finish as soon as the process exits or closes it's stdout. This should finish as soon as the process exits or closes it's stdout.
...@@ -58,7 +58,7 @@ def call_and_return_stdout(args: tp.Union[str, tp.List[str]], ...@@ -58,7 +58,7 @@ def call_and_return_stdout(args: tp.Union[str, tp.List[str]],
proc = subprocess.Popen(args, **kwargs) proc = subprocess.Popen(args, **kwargs)
reader_thread = threading.Thread(name='stdout reader', reader_thread = threading.Thread(name='stdout reader',
target=read_nowait, target=_read_nowait,
args=(proc, stdout_list), args=(proc, stdout_list),
daemon=True) daemon=True)
reader_thread.start() reader_thread.start()
......
import unittest import unittest
from satella.coding.concurrent import LockedDataset from satella.coding.concurrent import LockedDataset
from satella.coding.concurrent.locked_dataset import get_internal from satella.coding.concurrent.locked_dataset import _get_internal
from satella.coding.structures import Singleton from satella.coding.structures import Singleton
from satella.exceptions import WouldWaitMore, ResourceNotLocked from satella.exceptions import WouldWaitMore, ResourceNotLocked
...@@ -30,7 +30,7 @@ class TestLockedDataset(unittest.TestCase): ...@@ -30,7 +30,7 @@ class TestLockedDataset(unittest.TestCase):
self.assertEqual(a.counter, 1) self.assertEqual(a.counter, 1)
self.assertRaises(ResourceNotLocked, lambda: a.counter) self.assertRaises(ResourceNotLocked, lambda: a.counter)
get_internal(a) _get_internal(a)
def test_locked_dataset_singleton(self): def test_locked_dataset_singleton(self):
@Singleton @Singleton
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment