Install & Compatibility
Where this runs
tested against v2.1.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.558s · 53.3MB
glibcpy 3.10–3.920 runs
installs and imports cleanly · install 4.7s · import 0.529s · 54MB
55MB installed
● package 55MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
setup
✓ from crochet import setup
Initializes the Crochet library, starts the Twisted reactor in a thread, and connects Twisted's logs to Python's standard logging. Must be called once before using other Crochet features.
wait_for
✓ from crochet import wait_for
A decorator factory that makes an asynchronous Twisted function callable from blocking code, blocking until a result or timeout occurs.
run_in_reactor
✓ from crochet import run_in_reactor
A decorator that ensures the wrapped function runs in the Twisted reactor thread, returning an EventualResult for later blocking retrieval.
TimeoutError
✓ from crochet import TimeoutError
Exception raised by `wait_for` if the decorated function exceeds its specified timeout.
This quickstart demonstrates how to use `crochet.setup()` to initialize the library and `crochet.wait_for` to wrap an asynchronous Twisted function, making it callable from synchronous Python code. It includes examples of successful execution, handling `TimeoutError`, and propagating exceptions from the Twisted reactor thread back to the blocking caller. Ensure you have `twisted` installed (`pip install twisted`) to run this example.
from crochet import setup, wait_for, TimeoutError
from twisted.internet import defer
import time
import logging
import os
# Configure basic logging to see Twisted output
logging.basicConfig(level=logging.INFO)
# Initialize crochet - this starts the Twisted reactor in a thread
setup()
@wait_for(timeout=5.0)
def long_running_twisted_task(duration):
d = defer.Deferred()
# Simulate an asynchronous operation in Twisted's reactor thread
def _complete_task():
if os.environ.get('SIMULATE_FAILURE') == '1':
d.err(ValueError("Simulated Twisted failure!"))
else:
d.callback(f"Task completed in {duration} seconds")
from twisted.internet import reactor
reactor.callLater(duration, _complete_task)
return d
if __name__ == "__main__":
print("Starting Crochet example...")
try:
# Call the Twisted-backed function from blocking code
result = long_running_twisted_task(2.0)
print(f"Blocking call returned: {result}")
# Demonstrate a timeout
print("\nAttempting a task that will timeout...")
try:
long_running_twisted_task(6.0) # Will timeout after 5 seconds
except TimeoutError:
print("Caught expected TimeoutError!")
# Demonstrate a Twisted error propagating
print("\nAttempting a task that will fail in Twisted...")
os.environ['SIMULATE_FAILURE'] = '1'
try:
long_running_twisted_task(1.0)
except ValueError as e:
print(f"Caught expected ValueError: {e}")
finally:
del os.environ['SIMULATE_FAILURE']
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
print("Crochet example finished.")
Errors
Common errors & fixes
RuntimeError: The Twisted reactor is not running, or has not been initialized by crochet.
`crochet.setup()` has not been called before attempting to use `@wait_for` or `EventualResult`.
fixAdd `from crochet import setup; setup()` to the initialization section of your application.
crochet.TimeoutError: Waited for 5.0 seconds
An operation decorated with `@wait_for(timeout=X)` exceeded the allowed X seconds, or the Twisted reactor got stuck.
fixIncrease the `timeout` parameter in the `@wait_for` decorator if the operation legitimately takes longer, or debug the Twisted code to identify why it's not completing.
ImportError: cannot import name 'wait_for' from 'crochet'
Attempting to import `wait_for` from a very old version of crochet, or a typo in the import statement.
fixEnsure `crochet` is installed and updated to a recent version (`pip install --upgrade crochet`). The common import is `from crochet import wait_for`.
Upgrade
Version history
2.1.1latest on PyPI · released Jul 1, 2023
Audit
Dependencies
twistedrequiredCore dependency for asynchronous operations.
wraptrequiredUsed for decorator functionality.