https://github.com/njsmith/deadline-scopes
https://github.com/njsmith/deadline-scopes
Last synced: about 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/njsmith/deadline-scopes
- Owner: njsmith
- Created: 2018-01-11T08:39:17.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2018-01-11T09:41:07.000Z (over 7 years ago)
- Last Synced: 2025-03-23T19:51:21.465Z (2 months ago)
- Language: Python
- Size: 2.93 KB
- Stars: 8
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.rst
Awesome Lists containing this project
README
========================================
Deadline scopes for synchronous Python
========================================This is a proof-of-concept implementation of Trio-style cancel scopes
for synchronous Python code, as described in my post `Timeouts and
cancellation for humans
`__. It
makes it easy to implement abstractable, composable, user-friendly
timeout support.Compared to Trio's cancel scopes, this library has a limitation: it
only supports time-based cancellation, not cancellation in response to
arbitrary events (that is, there's no ``cancel_scope.cancel()``
method) – that's why I call it "deadline scopes" instead of "cancel
scopes". This limitation is imposed by the underlying Python standard
library primitives it uses. However, this mostly isn't a big deal,
since if a single-threaded synchronous program is stuck inside some
blocking operation, then who would call cancel anyway?This is an experiment, and I'm not sure how much time I'll spend
developing it further – see `Trio `__ for
a more complete Python I/O solution. But if you want to pick it up and
run with it, then go for it. Or I guess it wouldn't be too hard to add
support to ``requests``, since `we're working on rewriting its I/O
layer anyway... hmm `__.Example
=======.. code-block:: python
from deadline_scopes import deadline_socket, fail_after
sock = deadline_socket() # like socket.socket()
# 5 second timeout on everything inside this block
with fail_after(5):
# Make a request to http://httpbin.org/delay/10, which should
# take 10 seconds to complete
print("connection")
sock.connect(("httpbin.org", 80))
print("sending")
sock.sendall(b"GET /delay/10 HTTP/1.1\r\nHost: httpbin.org\r\n\r\n")
while True:
# Read and discard body
data = sock.recv(1024)
print(data)
if not data:
breakSee the code for more details.