Typing Stubs for gevent
types-gevent provides external type annotations (stubs) for the gevent library. It enables static type checkers like MyPy and Pyright to perform type checking, inference, and autocompletion for code that uses gevent. As part of the typeshed project, its releases are automatically generated and follow a versioning scheme tied to the gevent runtime package version.
Warnings
- breaking Type stubs are version-specific. Installing 'types-gevent' for 'gevent==X.Y' alongside a different version of 'gevent' (e.g., 'gevent==A.B' where A.B != X.Y) can lead to incorrect type checking errors or missed type issues. The 'types-gevent' package version `X.Y.Z.YYYYMMDD` indicates it targets `gevent==X.Y.*`.
- gotcha Stub packages like 'types-gevent' provide static type information only; they do not include any runtime code or functionality. Installing 'types-gevent' without the actual 'gevent' library will not make 'gevent' available for execution.
- gotcha When using `gevent.monkey.patch_all()`, the patching must occur as early as possible in your application's lifecycle, typically at the very beginning of your main script. Delaying patching, especially after other standard library modules (e.g., `concurrent.futures`, `threading`) have been imported, can result in those modules retaining their original blocking behavior or lead to conflicts.
- gotcha Gevent is designed for I/O-bound concurrency, not CPU-bound parallelism. Running CPU-intensive tasks within a greenlet will block the entire event loop, preventing other greenlets from executing and negating the benefits of cooperative multitasking.
- gotcha Combining `gevent` with Python's built-in `multiprocessing` module can introduce complex issues and is generally discouraged without careful management. Specifically, after forking on POSIX systems, `gevent`'s internal state in the child process can be ill-posed, leading to unexpected behavior.
Install
-
pip install types-gevent
Imports
- gevent
import gevent
- gevent.monkey
import gevent.monkey
Quickstart
import gevent
import gevent.monkey
import typing
gevent.monkey.patch_all()
def fetch_data(url: str) -> str:
"""Simulates fetching data asynchronously."""
gevent.sleep(0.1) # Simulate I/O delay
return f"Data from {url}"
def process_urls(urls: typing.List[str]) -> typing.List[str]:
greenlets = [gevent.spawn(fetch_data, url) for url in urls]
gevent.joinall(greenlets)
results = [g.value for g in greenlets]
return results
if __name__ == "__main__":
urls_to_process = ["http://example.com/1", "http://example.com/2"]
processed_data = process_urls(urls_to_process)
print(f"Processed: {processed_data}")
# To run type checking, save this as e.g., 'main.py' and run:
# mypy main.py