diff --git a/stream2py/buffer_reader.py b/stream2py/buffer_reader.py index cc669df..7dc10bf 100644 --- a/stream2py/buffer_reader.py +++ b/stream2py/buffer_reader.py @@ -151,6 +151,7 @@ def __init__( self._read_kwargs_for_next = dict(self._read_kwargs, ignore_no_item_found=True) def __iter__(self): + """Iterate over the items.""" while True: try: _next = next(self) @@ -382,6 +383,7 @@ def tail(self, *, peek=False, ignore_no_item_found=False, only_new_items=False): return item def head(self, *, peek=False): + """The first item in the buffer; with ``peek=True`` the read cursor is not moved.""" with self._buffer.reader_lock() as reader: item = reader[0] if not peek: @@ -490,6 +492,7 @@ def read( return next_item def next(self, n=1, *, peek=False, ignore_no_item_found=False, strict_n=False): + """Deprecated alias of :meth:`read`.""" from warnings import warn warn( @@ -501,20 +504,26 @@ def next(self, n=1, *, peek=False, ignore_no_item_found=False, strict_n=False): ) def enter(self): + """Alias of ``__enter__``.""" return self.open() def exit(self): + """Alias of ``__exit__``.""" return self.close() def open(self): + """Open the resource.""" return self def close(self): + """Close the resource.""" if self.onclose: self.onclose() def __enter__(self): + """Enter the context (start or open the resource) and return it.""" return self.enter() def __exit__(self, exc_type, exc_val, exc_tb): + """Leave the context (stop or close the resource).""" return self.exit() diff --git a/stream2py/protocols.py b/stream2py/protocols.py index 3e44abc..fb2718e 100644 --- a/stream2py/protocols.py +++ b/stream2py/protocols.py @@ -7,18 +7,24 @@ class Source(Protocol): """The interface for the StreamSource class.""" - def key(self, data) -> Any: ... + def key(self, data) -> Any: + """Sort key of ``data``.""" @property def info(self) -> dict: + """Information about the source.""" return {} @property def sleep_time_on_read_none_s(self) -> int: + """Seconds to wait when ``read`` returns ``None``.""" return 0 - def read(self) -> Any: ... + def read(self) -> Any: + """Read the next item, or ``None`` if nothing is ready.""" - def open(self) -> None: ... + def open(self) -> None: + """Open the resource.""" - def close(self) -> None: ... + def close(self) -> None: + """Close the resource.""" diff --git a/stream2py/source_reader.py b/stream2py/source_reader.py index f88833f..1e7e52d 100644 --- a/stream2py/source_reader.py +++ b/stream2py/source_reader.py @@ -79,6 +79,7 @@ class SourceReader(Source, metaclass=ABCMeta): _closed = True # SourceReader starts in closed state def __iter__(self): + """Iterate over the items.""" while True: _next = self.read() if _next is not None: @@ -192,11 +193,13 @@ def get_timestamp(cls) -> int: return int(time.time() * cls.timestamp_seconds_to_unit_conversion) def __enter__(self): + """Enter the context (start or open the resource) and return it.""" self.open() self._closed = False return self def __exit__(self, exc_type, exc_val, exc_tb) -> None: + """Leave the context (stop or close the resource).""" self.close() self._closed = True @@ -208,6 +211,7 @@ def stream_buffer( sleep_time_on_read_none_s: Optional[Union[int, float]] = None, auto_drop=True, ): + """A :class:`StreamBuffer` fed by this reader, holding up to ``maxlen`` items.""" from stream2py.stream_buffer import StreamBuffer return StreamBuffer( diff --git a/stream2py/sources/http.py b/stream2py/sources/http.py index a9f8a25..2479549 100644 --- a/stream2py/sources/http.py +++ b/stream2py/sources/http.py @@ -18,6 +18,7 @@ class HTTPResponseReader(SourceReader): + """Source reader that streams the raw bytes of an HTTP response.""" _request: urllib.request.Request _n_bytes_read: int _init_kwargs: dict @@ -98,12 +99,14 @@ def key(self, data) -> ComparableType: # return self._data[data[0]:data[1]] def open(self): + """Open the resource.""" request = urllib.request.Request( self._url, headers=self._init_kwargs["headers"] ) self._response = urllib.request.urlopen(request) def close(self): + """Close the resource.""" if self._response: self._response.__exit__() self._response = None diff --git a/stream2py/stream_buffer.py b/stream2py/stream_buffer.py index d67ccba..390b98e 100644 --- a/stream2py/stream_buffer.py +++ b/stream2py/stream_buffer.py @@ -180,10 +180,12 @@ def __init__( self._read_to_buffer_thread = None def __iter__(self): + """Iterate over the items.""" reader = self.mk_reader() yield from iter(reader) def __next__(self): + """The next item.""" if self._next_reader is None: self._next_reader = self.mk_reader() return next(self._next_reader) @@ -264,13 +266,16 @@ def is_running(self) -> bool: @property def join(self): + """Join the thread that fills the buffer.""" return self._read_to_buffer_thread.join def __enter__(self): + """Enter the context (start or open the resource) and return it.""" self.start() return self def __exit__(self, exc_type, exc_val, exc_tb): + """Leave the context (stop or close the resource).""" self.stop() enter, exit = __enter__, __exit__ @@ -337,6 +342,7 @@ def __call__(self): # return self._mk_contextualized_iterator() def __del__(self): + """Stop the resource when garbage collected, ignoring errors.""" try: self.__exit__(None, None, None) except Exception: diff --git a/stream2py/stream_source.py b/stream2py/stream_source.py index 009fd07..c1969f0 100644 --- a/stream2py/stream_source.py +++ b/stream2py/stream_source.py @@ -64,9 +64,11 @@ class StreamSource(Source, metaclass=ABCMeta): _stream_buffer: StreamBuffer = None def __init__(self, *, reader_cls=BufferReader): + """Initialize the instance; see the class docstring for the arguments.""" self._reader_cls = reader_cls def __iter__(self): + """Iterate over the items.""" while True: _next = self.read() if _next is not None: @@ -165,6 +167,7 @@ def get_timestamp(cls) -> int: return int(time.time() * cls.timestamp_seconds_to_unit_conversion) def exit(self): + """Alias of ``__exit__``.""" if self._stream_buffer: self._stream_buffer.stop() else: diff --git a/stream2py/tests/test_rw_lock.py b/stream2py/tests/test_rw_lock.py new file mode 100644 index 0000000..7fb969f --- /dev/null +++ b/stream2py/tests/test_rw_lock.py @@ -0,0 +1,55 @@ +"""Tests for the readers-writer lock: shared reads, exclusive writes (deterministic, no sleeps).""" + +import threading + +from stream2py.utility.reader_writer_lock import RWLock + +WAIT = ( + 5.0 # generous upper bound; every wait below is released by an event, not by time +) + + +def _in_thread(fn): + done = threading.Event() + + def run(): + fn() + done.set() + + threading.Thread(target=run, daemon=True).start() + return done + + +def test_many_readers_hold_the_lock_at_once(): + lock = RWLock() + lock.reader_acquire() + second = _in_thread(lambda: (lock.reader_acquire(), lock.reader_release())) + assert second.wait(WAIT), "a second reader must not block while a reader holds" + lock.reader_release() + + +def test_a_writer_waits_for_the_last_reader(): + lock = RWLock() + lock.reader_acquire() + wrote = _in_thread(lambda: (lock.writer_acquire(), lock.writer_release())) + assert not wrote.wait(0.2), "a writer must wait while a reader holds" + lock.reader_release() + assert wrote.wait(WAIT) + + +def test_a_reader_waits_for_the_writer(): + lock = RWLock() + lock.writer_acquire() + read = _in_thread(lambda: (lock.reader_acquire(), lock.reader_release())) + assert not read.wait(0.2), "a reader must wait while a writer holds" + lock.writer_release() + assert read.wait(WAIT) + + +def test_writers_exclude_each_other(): + lock = RWLock() + lock.writer_acquire() + other = _in_thread(lambda: (lock.writer_acquire(), lock.writer_release())) + assert not other.wait(0.2) + lock.writer_release() + assert other.wait(WAIT) diff --git a/stream2py/tests/test_simply.py b/stream2py/tests/test_simply.py new file mode 100644 index 0000000..a2aea4c --- /dev/null +++ b/stream2py/tests/test_simply.py @@ -0,0 +1,68 @@ +"""Tests for ``mk_stream_buffer``: open/close wiring, enumeration, key and info seams.""" + +import itertools + +from stream2py.simply import mk_stream_buffer +from stream2py.tests.utils_for_testing import wait_until + + +def _finite(n): + it = iter(range(n)) + return lambda open_inst: next(it, None) + + +def test_open_and_close_are_called_once_and_data_is_enumerated(): + events = [] + with mk_stream_buffer( + read_stream=_finite(5), + open_stream=lambda: events.append("open") or "handle", + close_stream=lambda inst: events.append(("close", inst)), + sleep_time_on_read_none_seconds=0.01, + maxlen=None, + ) as buf: + assert wait_until(lambda: len(buf.source_buffer) >= 5) + items = buf.mk_reader().read(n=5, ignore_no_item_found=True) + assert [i for i, _ in items] == [0, 1, 2, 3, 4] + assert [d for _, d in items] == [0, 1, 2, 3, 4] + # closing happens on the buffer thread as it winds down: wait for it, don't assume + assert wait_until(lambda: len(events) == 2) + assert events == ["open", ("close", "handle")] + + +def test_enumerate_data_false_keeps_raw_items_and_key_orders_them(): + with mk_stream_buffer( + read_stream=_finite(4), + enumerate_data=False, + key=lambda x: x, + sleep_time_on_read_none_seconds=0.01, + maxlen=None, + ) as buf: + assert wait_until(lambda: len(buf.source_buffer) >= 4) + reader = buf.mk_reader() + assert reader.read(n=4, ignore_no_item_found=True) == [0, 1, 2, 3] + + +def test_default_info_reports_open_time_and_instance_and_custom_info_wins(): + with mk_stream_buffer( + read_stream=_finite(1), + open_stream=lambda: "inst", + sleep_time_on_read_none_seconds=0.01, + ) as buf: + info = buf.mk_reader().source_reader_info + assert info["open_instance"] == "inst" and info["open_time"] > 0 + with mk_stream_buffer( + read_stream=_finite(1), + open_stream=lambda: "inst", + info=lambda inst: {"custom": inst}, + sleep_time_on_read_none_seconds=0.01, + ) as buf: + assert buf.mk_reader().source_reader_info == {"custom": "inst"} + + +def test_without_open_or_close_callbacks_the_stream_still_runs(): + counter = itertools.count() + with mk_stream_buffer( + read_stream=lambda inst: next(counter) if next(counter) < 3 else None, + sleep_time_on_read_none_seconds=0.01, + ) as buf: + assert wait_until(lambda: len(buf.source_buffer) >= 1) diff --git a/stream2py/tests/test_sorted_containers.py b/stream2py/tests/test_sorted_containers.py new file mode 100644 index 0000000..7c1cd60 --- /dev/null +++ b/stream2py/tests/test_sorted_containers.py @@ -0,0 +1,162 @@ +"""Tests for ``SortedCollection`` and ``SortedDeque`` (search, ordering, copy/pickle, error paths).""" + +import pickle + +import pytest + +from stream2py.utility.sorted_collection import SortedCollection +from stream2py.utility.sorted_deque import SortedDeque + +KINDS = [SortedCollection, SortedDeque] + + +def _pair(n): + return (n, f"v{n}") + + +@pytest.fixture(params=KINDS) +def cls(request): + return request.param + + +def test_construction_sorts_by_key(cls): + c = cls([(3, "c"), (1, "a"), (2, "b")], key=lambda p: p[0]) + assert list(c) == [(1, "a"), (2, "b"), (3, "c")] + assert len(c) == 3 and c[0] == (1, "a") and list(reversed(c))[0] == (3, "c") + + +def test_insert_left_vs_right_for_equal_keys(cls): + if cls is SortedDeque: + pytest.skip("a SortedDeque inserts by append; covered separately") + c = cls([("a", 1)], key=lambda p: p[1]) + c.insert(("b", 1)) + c.insert_right(("c", 1)) + assert [x[0] for x in c] == ["b", "a", "c"] + + +def test_contains_index_count_and_remove(cls): + c = cls([(1, "a"), (2, "b"), (2, "b"), (3, "c")], key=lambda p: p[0]) + assert (2, "b") in c and (2, "x") not in c and (9, "z") not in c + assert c.index((2, "b")) == 1 + assert c.count((2, "b")) == 2 and c.count((9, "z")) == 0 + with pytest.raises(ValueError): + c.index((2, "x")) + if cls is SortedCollection: + c.remove((2, "b")) + assert c.count((2, "b")) == 1 + with pytest.raises(ValueError): + c.remove((9, "z")) + + +def test_find_family(cls): + c = cls([_pair(n) for n in (10, 20, 30)], key=lambda p: p[0]) + assert c.find(20) == (20, "v20") + assert c.find_le(25) == (20, "v20") and c.find_le(20) == (20, "v20") + assert c.find_lt(20) == (10, "v10") + assert c.find_ge(25) == (30, "v30") and c.find_ge(20) == (20, "v20") + assert c.find_gt(20) == (30, "v30") + for call, k in [ + (c.find, 25), + (c.find_le, 5), + (c.find_lt, 10), + (c.find_ge, 31), + (c.find_gt, 30), + ]: + with pytest.raises(ValueError): + call(k) + + +def test_key_property_set_rebuilds_and_del_restores_identity(cls): + c = cls([(2, 1), (1, 2)], key=lambda p: p[0]) + assert list(c) == [(1, 2), (2, 1)] + c.key = lambda p: p[1] + assert list(c) == [(2, 1), (1, 2)] + del c.key + assert list(c) == [(1, 2), (2, 1)] + + +def test_clear_and_copy_are_independent(cls): + c = cls([3, 1, 2]) + twin = c.copy() + c.clear() + assert len(c) == 0 and list(twin) == [1, 2, 3] + assert isinstance(twin, cls) + + +def test_repr_names_the_class_and_key(cls): + def by_first(p): + return p[0] + + assert "by_first" in repr(cls([(1, 2)], key=by_first)) + assert repr(cls([1])).startswith(cls.__name__) + + +def test_pickle_round_trip_with_a_named_key(cls): + c = cls([3, 1, 2], key=abs) + assert list(pickle.loads(pickle.dumps(c))) == [1, 2, 3] + + +# --- SortedDeque specifics --------------------------------------------------------------- + + +def test_maxlen_property_evicts_from_the_left(): + d = SortedDeque([1, 2, 3], maxlen=3) + d.append(4) + assert list(d) == [2, 3, 4] and d.maxlen == 3 + + +def test_append_requires_a_strictly_greater_key(): + d = SortedDeque([1, 2]) + with pytest.raises(ValueError, match="greater than last"): + d.append(2) + d.append(3) + assert list(d) == [1, 2, 3] + empty = SortedDeque() + empty.append(1) + assert list(empty) == [1] + + +def test_range_and_range_by_index(): + d = SortedDeque([_pair(n) for n in range(0, 50, 10)], key=lambda p: p[0]) + assert [p[0] for p in d.range(10, 30)] == [10, 20, 30] + assert [p[0] for p in d.range(10, 40, 2)] == [10, 30] + assert d.range(100, 200) == [] + assert [p[0] for p in d.range_by_index(1, 3)] == [10, 20] + + +def test_find_last_gt_and_drop(): + d = SortedDeque([1, 2, 3]) + assert d.find_last_gt(2) == 3 + with pytest.raises(ValueError): + d.find_last_gt(3) + with pytest.raises(ValueError): + SortedDeque().find_last_gt(0) + d.drop() + assert list(d) == [2, 3] + d.drop(2) + assert len(d) == 0 + + +def test_jdict_round_trip(): + d = SortedDeque([3, 1, 2], maxlen=5) + params = d.to_jdict() + assert params["maxlen"] == 5 and params["iterable"] == [1, 2, 3] + assert list(SortedDeque.from_jdict(params)) == [1, 2, 3] + + +def test_deque_copy_keeps_maxlen(): + d = SortedDeque([1, 2], maxlen=2) + twin = d.copy() + twin.append(3) + assert list(twin) == [2, 3] and list(d) == [1, 2] + + +def test_insert_into_a_full_deque_raises_and_leaves_it_unchanged(): + """Pins current behaviour: ``insert`` (unlike ``append``) does not evict at ``maxlen``.""" + d = SortedDeque([1, 2, 3], maxlen=3) + with pytest.raises(IndexError): + d.insert(0) + assert list(d) == [1, 2, 3] + d2 = SortedDeque([1, 3], maxlen=5) + d2.insert(2) + assert list(d2) == [1, 2, 3] diff --git a/stream2py/tests/test_util.py b/stream2py/tests/test_util.py index fcdff7b..a9dbd1f 100644 --- a/stream2py/tests/test_util.py +++ b/stream2py/tests/test_util.py @@ -203,3 +203,21 @@ def test_timer_stop_accepts_context_manager_exit_args(): timer = Timer().start() timer.stop(ValueError, ValueError('x'), None) assert timer.start_time is None + + +@pytest.mark.xfail( + strict=True, + reason="https://github.com/i2mint/stream2py/issues/33: the variadic check is not called", +) +def test_exit_function_validation_rejects_a_one_argument_function(): + from stream2py.util import ExitFunctionValidation + + assert not ExitFunctionValidation.is_valid(lambda obj: None) + + +def test_exit_function_validation_accepts_variadic_and_four_argument_functions(): + from stream2py.util import ExitFunctionValidation + + assert ExitFunctionValidation.is_valid(lambda obj, *info: None) + assert ExitFunctionValidation.is_valid(lambda obj, a, b, c: None) + assert not ExitFunctionValidation.is_valid(42) diff --git a/stream2py/util.py b/stream2py/util.py index a035265..018ebae 100644 --- a/stream2py/util.py +++ b/stream2py/util.py @@ -58,14 +58,17 @@ class Timer: """ def __init__(self, egress=identity): + """Initialize the instance; see the class docstring for the arguments.""" self.egress = egress self.start_time = None def start(self): + """Start the timer and return it.""" self.start_time = perf_counter() return self def stop(self, *args, **kwargs): + """Stop (reset) the timer.""" self.start_time = None def elapsed(self): @@ -95,15 +98,18 @@ def is_valid(obj) -> bool: @classmethod def validate(cls, obj, *args, **kwargs): + """Raise ``cls(*args, **kwargs)`` unless ``obj`` is valid.""" if not cls.is_valid(obj): raise cls(*args, **kwargs) def null_enter_func(obj): + """An enter function that returns the object itself.""" return obj def null_exit_func(obj, *exception_info): + """An exit function that does nothing.""" return None @@ -124,6 +130,7 @@ class EnterFunctionValidation(TypeValidationError): @staticmethod def is_valid(obj): + """Whether ``obj`` is a valid function of this kind.""" return callable(obj) and _has_min_num_of_arguments(obj, 1) @@ -132,6 +139,7 @@ class ExitFunctionValidation(TypeValidationError): @staticmethod def is_valid(obj): + """Whether ``obj`` is a valid function of this kind.""" return callable(obj) and ( _callable_has_a_variadic_pos or _has_min_num_of_arguments(obj, 4) ) @@ -190,6 +198,7 @@ class ContextualizeCall: """ def __init__(self, func, enter_func=null_enter_func, exit_func=null_exit_func): + """Initialize the instance; see the class docstring for the arguments.""" # validation if not callable(func): raise TypeError(f"First argument should be a callable, was: {func}") @@ -211,17 +220,21 @@ def __init__(self, func, enter_func=null_enter_func, exit_func=null_exit_func): wraps(func)(self) def __call__(self, *args, **kwargs): + """Call the wrapped function.""" return self.func(*args, **kwargs) def __enter__(self): + """Enter the context (start or open the resource) and return it.""" # print(f'{type(self).__name__}.__enter__') return self.enter_func(self.func) def __exit__(self, exc_type, exc_val, exc_tb): + """Leave the context (stop or close the resource).""" # print(f'{type(self).__name__}.__exit__') return self.exit_func(self.func, exc_type, exc_val, exc_tb) def __getattr__(self, attrname): + """Forward unknown attributes to the wrapped function.""" return getattr(self.func, attrname) @@ -234,10 +247,12 @@ def __getattr__(self, attrname): def forward_to_instance_enter(obj): + """Call ``__enter__`` on the instance a bound method belongs to.""" return obj.__self__.__enter__() def forward_to_instance_exit(obj, *exception_info): + """Call ``__exit__`` on the instance a bound method belongs to.""" return obj.__self__.__exit__(*exception_info) diff --git a/stream2py/utility/locked_sorted_deque.py b/stream2py/utility/locked_sorted_deque.py index 536b679..afafede 100644 --- a/stream2py/utility/locked_sorted_deque.py +++ b/stream2py/utility/locked_sorted_deque.py @@ -28,18 +28,22 @@ class RWLockSortedDeque(RWLock): """ def __init__(self, iterable=(), *, key=None, maxlen=None): + """Initialize the instance; see the class docstring for the arguments.""" RWLock.__init__(self) self._sorted_deque = SortedDeque(iterable, key, maxlen) def __len__(self): + """Number of items.""" return len(self._sorted_deque) @property def key(self): + """Sort key of ``data``.""" return self._sorted_deque.key @contextmanager def reader_lock(self) -> Generator[SortedDeque, None, None]: + """Context manager yielding the deque under a shared (reader) lock.""" try: self.reader_acquire() yield self._sorted_deque @@ -48,6 +52,7 @@ def reader_lock(self) -> Generator[SortedDeque, None, None]: @contextmanager def writer_lock(self): + """Context manager yielding the deque under the exclusive (writer) lock.""" try: self.writer_acquire() yield self._sorted_deque diff --git a/stream2py/utility/reader_writer_lock.py b/stream2py/utility/reader_writer_lock.py index 41c8da5..892ddd5 100644 --- a/stream2py/utility/reader_writer_lock.py +++ b/stream2py/utility/reader_writer_lock.py @@ -31,6 +31,7 @@ class RWLock: """ def __init__(self): + """Initialize the instance; see the class docstring for the arguments.""" self.__read_switch = _LightSwitch() self.__write_switch = _LightSwitch() self.__no_readers = threading.Lock() @@ -40,6 +41,7 @@ def __init__(self): cases (see [2] for a discussion)""" def reader_acquire(self): + """Acquire the lock for reading (shared).""" self.__readers_queue.acquire() self.__no_readers.acquire() self.__read_switch.acquire(self.__no_writers) @@ -47,13 +49,16 @@ def reader_acquire(self): self.__readers_queue.release() def reader_release(self): + """Release a read lock.""" self.__read_switch.release(self.__no_writers) def writer_acquire(self): + """Acquire the lock for writing (exclusive).""" self.__write_switch.acquire(self.__no_readers) self.__no_writers.acquire() def writer_release(self): + """Release the write lock.""" self.__no_writers.release() self.__write_switch.release(self.__no_readers) @@ -93,6 +98,7 @@ def release(self, lock): class Writer(threading.Thread): + """Thread that appends to a shared buffer under the write lock (used by the lock tests).""" def __init__(self, buffer_, rw_lock, init_sleep_time, sleep_time, to_write): """ @param buffer_: common buffer_ shared by the readers and writers @@ -116,6 +122,7 @@ def __init__(self, buffer_, rw_lock, init_sleep_time, sleep_time, to_write): """Time of exit from the critical section""" def run(self): + """Thread body: wait, take the lock, do the work, release.""" time.sleep(self.__init_sleep_time) self.__rw_lock.writer_acquire() self.entry_time = time.time() @@ -126,6 +133,7 @@ def run(self): class Reader(threading.Thread): + """Thread that copies a shared buffer under the read lock (used by the lock tests).""" def __init__(self, buffer_, rw_lock, init_sleep_time, sleep_time): """ @param buffer_: common buffer shared by the readers and writers @@ -149,6 +157,7 @@ def __init__(self, buffer_, rw_lock, init_sleep_time, sleep_time): """Time of exit from the critical section""" def run(self): + """Thread body: wait, take the lock, do the work, release.""" time.sleep(self.__init_sleep_time) self.__rw_lock.reader_acquire() self.entry_time = time.time() @@ -159,7 +168,9 @@ def run(self): class RWLockTestCase(unittest.TestCase): + """Unit tests for :class:`RWLock`.""" def test_readers_nonexclusive_access(self): + """Check readers nonexclusive access.""" (buffer_, rw_lock, threads) = self.__init_variables() threads.append(Reader(buffer_, rw_lock, 0, 0)) @@ -182,6 +193,7 @@ def test_readers_nonexclusive_access(self): self.assert_(threads[3].exit_time < threads[2].exit_time) def test_writers_exclusive_access(self): + """Check writers exclusive access.""" (buffer_, rw_lock, threads) = self.__init_variables() threads.append(Writer(buffer_, rw_lock, 0, 0.4, 1)) @@ -197,6 +209,7 @@ def test_writers_exclusive_access(self): self.assert_(threads[1].exit_time <= threads[2].exit_time) def test_writer_priority(self): + """Check writer priority.""" (buffer_, rw_lock, threads) = self.__init_variables() threads.append(Writer(buffer_, rw_lock, 0, 0, 1)) @@ -218,6 +231,7 @@ def test_writer_priority(self): self.assert_(threads[2].exit_time <= threads[4].entry_time) def test_many_writers_priority(self): + """Check many writers priority.""" (buffer_, rw_lock, threads) = self.__init_variables() threads.append(Writer(buffer_, rw_lock, 0, 0, 1)) diff --git a/stream2py/utility/sorted_collection.py b/stream2py/utility/sorted_collection.py index 4da43e5..66dd5f0 100644 --- a/stream2py/utility/sorted_collection.py +++ b/stream2py/utility/sorted_collection.py @@ -77,6 +77,7 @@ class SortedCollection(object): """ def __init__(self, iterable=(), key=None): + """Initialize the instance; see the class docstring for the arguments.""" self._given_key = key key = (lambda x: x) if key is None else key decorated = sorted((key(item), item) for item in iterable) @@ -97,24 +98,31 @@ def _delkey(self): key = property(_getkey, _setkey, _delkey, "key function") def clear(self): + """Remove all items.""" self.__init__([], self._key) def copy(self): + """A shallow copy with the same key.""" return self.__class__(self, self._key) def __len__(self): + """Number of items.""" return len(self._items) def __getitem__(self, i): + """The item at the given index.""" return self._items[i] def __iter__(self): + """Iterate over the items.""" return iter(self._items) def __reversed__(self): + """Iterate over the items in reverse.""" return reversed(self._items) def __repr__(self): + """Show the contents and key.""" return "%s(%r, key=%s)" % ( self.__class__.__name__, self._items, @@ -122,9 +130,11 @@ def __repr__(self): ) def __reduce__(self): + """Pickle support: rebuild from items and key.""" return self.__class__, (self._items, self._given_key) def __contains__(self, item): + """Whether the item is present (compared by key first).""" k = self._key(item) i = bisect_left(self._keys, k) j = bisect_right(self._keys, k) diff --git a/stream2py/utility/sorted_deque.py b/stream2py/utility/sorted_deque.py index a136712..3e91d12 100644 --- a/stream2py/utility/sorted_deque.py +++ b/stream2py/utility/sorted_deque.py @@ -20,6 +20,7 @@ class SortedDeque(SortedCollection): """ def __init__(self, iterable=(), key=None, maxlen=None): + """Initialize the instance; see the class docstring for the arguments.""" SortedCollection.__init__(self, iterable, key) self._keys = deque(self._keys, maxlen=maxlen) self._items = deque(self._items, maxlen=maxlen) @@ -35,6 +36,7 @@ def to_jdict(self): @classmethod def from_jdict(cls, params_dict): + """Build from the dict made by :meth:`to_jdict`.""" return cls(**params_dict) def _getmaxlen(self): @@ -54,12 +56,15 @@ def _setkey(self, key): self.__init__(self._items, key=key, maxlen=self._maxlen) def clear(self): + """Remove all items.""" self.__init__([], self._key, self._maxlen) def copy(self): + """A shallow copy with the same key.""" return self.__class__(self, self._key, self._maxlen) def __repr__(self): + """Show the contents and key.""" return "%s(%r, key=%s, maxlen=%s)" % ( self.__class__.__name__, list(self._items), # Not sure if this is the best way to do this @@ -68,9 +73,11 @@ def __repr__(self): ) def __reduce__(self): + """Pickle support: rebuild from items and key.""" return self.__class__, (self._items, self._given_key, self._maxlen) def __contains__(self, item): + """Whether the item is present (compared by key first).""" k = self._key(item) i = bisect_left(self._keys, k) j = bisect_right(self._keys, k) diff --git a/stream2py/utility/typing_hints.py b/stream2py/utility/typing_hints.py index 420eec4..203e8b1 100644 --- a/stream2py/utility/typing_hints.py +++ b/stream2py/utility/typing_hints.py @@ -6,6 +6,10 @@ class ComparableType(Protocol): - def __lt__(self, other: Any) -> bool: ... + """Protocol for keys that support ``<`` and ``>``.""" - def __gt__(self, other: Any) -> bool: ... + def __lt__(self, other: Any) -> bool: + """Less-than comparison.""" + + def __gt__(self, other: Any) -> bool: + """Greater-than comparison."""