Workers API Reference¶
Worker Decorator¶
concurry.core.worker.base_worker.worker(cls: Optional[Type[T]] = None, *, mode: Union[ExecutionMode, _NO_ARG_TYPE] = _NO_ARG, blocking: Union[bool, _NO_ARG_TYPE] = _NO_ARG, max_workers: Optional[Union[conint(ge=0), _NO_ARG_TYPE]] = _NO_ARG, load_balancing: Union[LoadBalancingAlgorithm, _NO_ARG_TYPE] = _NO_ARG, on_demand: Union[bool, _NO_ARG_TYPE] = _NO_ARG, max_queued_tasks: Optional[Union[conint(ge=0), _NO_ARG_TYPE]] = _NO_ARG, num_retries: Union[conint(ge=0), dict[str, conint(ge=0)], _NO_ARG_TYPE] = _NO_ARG, retry_on: Union[Any, dict[str, Any], _NO_ARG_TYPE] = _NO_ARG, retry_algorithm: Union[RetryAlgorithm, dict[str, RetryAlgorithm], _NO_ARG_TYPE] = _NO_ARG, retry_wait: Union[confloat(ge=0), dict[str, confloat(ge=0)], _NO_ARG_TYPE] = _NO_ARG, retry_jitter: Union[confloat(ge=0, le=1), dict[str, confloat(ge=0, le=1)], _NO_ARG_TYPE] = _NO_ARG, retry_until: Union[Any, dict[str, Any], _NO_ARG_TYPE] = _NO_ARG, unwrap_futures: Union[bool, _NO_ARG_TYPE] = _NO_ARG, limits: Optional[Any] = None, auto_init: Union[bool, _NO_ARG_TYPE] = _NO_ARG, **kwargs: Any) -> Union[Callable[[Type[T]], Type[T]], Type[T]]
¶
Decorator to create a Worker class with pre-configured options.
This decorator accepts all Worker.options() parameters and stores them for automatic application when the class is instantiated.
Can be used with or without parameters:
- @worker (no params)
- @worker(mode='thread', max_workers=4, auto_init=True)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
Optional[Type[T]]
|
The class to decorate (when used without parentheses) |
None
|
mode
|
Union[ExecutionMode, _NO_ARG_TYPE]
|
Execution mode (sync, thread, process, asyncio, ray) |
_NO_ARG
|
blocking
|
Union[bool, _NO_ARG_TYPE]
|
Whether to return results directly |
_NO_ARG
|
max_workers
|
Optional[Union[conint(ge=0), _NO_ARG_TYPE]]
|
Number of workers for pool |
_NO_ARG
|
auto_init
|
Union[bool, _NO_ARG_TYPE]
|
Whether direct instantiation creates workers (default: True if any param) |
_NO_ARG
|
num_retries
|
Union[conint(ge=0), dict[str, conint(ge=0)], _NO_ARG_TYPE]
|
Maximum number of retry attempts after initial failure |
_NO_ARG
|
retry_on
|
Union[Any, dict[str, Any], _NO_ARG_TYPE]
|
Exception types or callables that trigger retries |
_NO_ARG
|
retry_algorithm
|
Union[RetryAlgorithm, dict[str, RetryAlgorithm], _NO_ARG_TYPE]
|
Backoff strategy for wait times |
_NO_ARG
|
retry_wait
|
Union[confloat(ge=0), dict[str, confloat(ge=0)], _NO_ARG_TYPE]
|
Minimum wait time between retries in seconds |
_NO_ARG
|
retry_jitter
|
Union[confloat(ge=0, le=1), dict[str, confloat(ge=0, le=1)], _NO_ARG_TYPE]
|
Jitter factor between 0 and 1 |
_NO_ARG
|
retry_until
|
Union[Any, dict[str, Any], _NO_ARG_TYPE]
|
Validation functions for output |
_NO_ARG
|
unwrap_futures
|
Union[bool, _NO_ARG_TYPE]
|
If True, automatically unwrap BaseFuture arguments |
_NO_ARG
|
limits
|
Optional[Any]
|
Resource protection and rate limiting |
None
|
load_balancing
|
Union[LoadBalancingAlgorithm, _NO_ARG_TYPE]
|
Load balancing algorithm |
_NO_ARG
|
on_demand
|
Union[bool, _NO_ARG_TYPE]
|
If True, create workers on-demand per request |
_NO_ARG
|
max_queued_tasks
|
Optional[Union[conint(ge=0), _NO_ARG_TYPE]]
|
Maximum number of in-flight tasks per worker |
_NO_ARG
|
**kwargs
|
Any
|
Mode-specific options |
{}
|
Returns:
| Type | Description |
|---|---|
Union[Callable[[Type[T]], Type[T]], Type[T]]
|
Decorated class or decorator function |
Examples:
Decorator Only:
@worker(mode='thread', max_workers=4, auto_init=True)
class LLM:
def __init__(self, model_name: str):
self.model_name = model_name
# Direct instantiation creates worker
llm = LLM(model_name='gpt-4')
future = llm.call_llm("What is 1+1?")
Without Parameters (Backward Compatible):
@worker
class LLM(Worker):
...
# Must use .options().init() (no auto_init)
llm = LLM.options(mode='thread').init(...)
Override at Instantiation:
@worker(mode='thread', max_workers=4)
class LLM:
...
# Override mode, keep max_workers
llm = LLM.options(mode='process').init(...)
Warns:
| Type | Description |
|---|---|
Mixing decorator and inheritance parameters is discouraged
|
Source code in src/concurry/core/worker/base_worker.py
3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 | |
Base Worker Class¶
concurry.core.worker.base_worker.Worker
¶
Base class for workers in concurry.
This class provides the foundation for user-defined workers. Users should inherit from this class and implement their worker logic. The worker will be automatically managed by the executor.
The Worker class implements the actor pattern, allowing you to run methods in different execution contexts (sync, thread, process, asyncio, ray) while maintaining state isolation and providing a unified Future-based API.
Important Design Note:
The Worker class itself does NOT inherit from morphic.Typed. This design choice allows you
complete freedom in defining your __init__ method - you can use any signature with any
combination of positional arguments, keyword arguments, args, and *kwargs. The Typed
integration is applied at the WorkerProxy layer, which wraps your worker and provides
validation for worker configuration (mode, blocking, etc.) but not for worker initialization.
Model Inheritance Support:
Worker supports cooperative multiple inheritance, allowing you to combine Worker with model classes for automatic field validation and serialization:
- ✅ morphic.Typed: Full support (ALL modes including Ray via automatic composition wrapper)
- ✅ pydantic.BaseModel: Full support (ALL modes including Ray via automatic composition wrapper)
- ✅ Ray mode: Fully compatible with Typed/BaseModel workers (automatic composition wrapper)
Validation Decorators (Works with ALL modes including Ray):
- ✅ @morphic.validate: Works on methods and init (all modes including Ray)
- ✅ @pydantic.validate_call: Works on methods and init (all modes including Ray)
These decorators provide runtime validation without class inheritance.
Automatic Composition Wrapper:
When you use Worker + Typed or Worker + BaseModel, concurry automatically applies a composition wrapper that makes them work seamlessly with Ray mode. This happens transparently - no code changes needed! The wrapper: - Isolates infrastructure methods from user methods - Avoids Ray's serialization conflicts with Pydantic's setattr - Maintains full validation and type checking - Has zero performance overhead (optimized delegation)
This means you can use: - Plain Python classes (all modes including Ray) - Worker + morphic.Typed for validation and hooks (all modes including Ray ✅) - Worker + pydantic.BaseModel for Pydantic validation (all modes including Ray ✅) - @validate or @validate_call decorators on methods (all modes including Ray) - Dataclasses, Attrs, or any other class structure (all modes)
The only requirement is that your worker class is instantiable via __init__ with the
arguments you pass to .init().
Basic Usage
from concurry import Worker
class DataProcessor(Worker):
def __init__(self, multiplier: int):
self.multiplier = multiplier
self.count = 0
def process(self, value: int) -> int:
self.count += 1
return value * self.multiplier
# Initialize worker with thread execution
worker = DataProcessor.options(mode="thread").init(3)
future = worker.process(10)
result = future.result() # 30
worker.stop()
Context Manager (Automatic Cleanup): Workers and pools support context manager protocol for automatic cleanup:
```python
from concurry import Worker
class DataProcessor(Worker):
def __init__(self, multiplier: int):
self.multiplier = multiplier
def process(self, value: int) -> int:
return value * self.multiplier
# Context manager automatically calls .stop() on exit
with DataProcessor.options(mode="thread").init(3) as worker:
future = worker.process(10)
result = future.result() # 30
# Worker is automatically stopped here
# Works with pools too
with DataProcessor.options(mode="thread", max_workers=5).init(3) as pool:
results = [pool.process(i).result() for i in range(10)]
# All workers in pool are automatically stopped here
# Cleanup happens even on exceptions
with DataProcessor.options(mode="thread").init(3) as worker:
if some_error:
raise ValueError("Error occurred")
# Worker is still stopped despite exception
```
Model Inheritance Usage
from concurry import Worker
from morphic import Typed
from pydantic import BaseModel, Field
from typing import List, Optional
# Worker + Typed for validation and lifecycle hooks
class TypedWorker(Worker, Typed):
name: str
value: int = Field(default=0, ge=0)
tags: List[str] = []
@classmethod
def pre_initialize(cls, data: dict) -> None:
# Normalize data before validation
if 'name' in data:
data['name'] = data['name'].strip().title()
def compute(self, x: int) -> int:
return self.value * x
# Initialize with validated fields
worker = TypedWorker.options(mode="thread").init(
name="processor",
value=10,
tags=["ml", "preprocessing"]
)
result = worker.compute(5).result() # 50
worker.stop()
# Worker + Pydantic BaseModel for validation
class PydanticWorker(Worker, BaseModel):
name: str = Field(..., min_length=1, max_length=50)
age: int = Field(..., ge=0, le=150)
email: Optional[str] = None
def get_info(self) -> dict:
return {"name": self.name, "age": self.age, "email": self.email}
worker = PydanticWorker.options(mode="process").init(
name="Alice",
age=30,
email="alice@example.com"
)
info = worker.get_info().result()
worker.stop()
Validation Decorators (Ray-Compatible):
from concurry import Worker
from morphic import validate
from pydantic import validate_call
# @validate decorator works with ALL modes including Ray
class ValidatedWorker(Worker):
def __init__(self, multiplier: int):
self.multiplier = multiplier
@validate
def process(self, value: int, scale: float = 1.0) -> float:
'''Process with automatic type validation and coercion.'''
return (value * self.multiplier) * scale
# Works with Ray mode!
worker = ValidatedWorker.options(mode="ray").init(multiplier=5)
result = worker.process("10", scale="2.0").result() # "10" -> 10, "2.0" -> 2.0
# result = 100.0
worker.stop()
# @validate_call also works with ALL modes including Ray
class PydanticValidatedWorker(Worker):
def __init__(self, base: int):
self.base = base
@validate_call
def compute(self, x: int, y: int = 0) -> int:
'''Compute with Pydantic validation.'''
return (x + y) * self.base
# Also works with Ray mode!
worker = PydanticValidatedWorker.options(mode="ray").init(base=3)
result = worker.compute("5", y="2").result() # Strings coerced to ints
# result = 21
worker.stop()
Ray Mode Support with Typed/BaseModel (Automatic Composition Wrapper):
# ✅ WORKS: Typed/BaseModel workers fully supported in Ray mode!
from morphic import Typed
from pydantic import BaseModel, Field
class TypedWorker(Worker, Typed):
name: str
value: int = 0
# Works with Ray mode via automatic composition wrapper!
worker = TypedWorker.options(mode="ray").init(name="test", value=10)
result = worker.compute(5).result() # 50
worker.stop()
# ✅ Pydantic BaseModel also works with Ray
class PydanticWorker(Worker, BaseModel):
name: str = Field(..., min_length=1)
value: int = Field(default=0, ge=0)
def compute(self, x: int) -> int:
return self.value * x
# Fully supported in Ray mode!
worker = PydanticWorker.options(mode="ray").init(name="test", value=10)
result = worker.compute(5).result() # 50
worker.stop()
# ✅ Validation decorators also work with Ray
class ValidatedRayWorker(Worker):
@validate
def __init__(self, name: str, value: int = 0):
self.name = name
self.value = value
@validate
def compute(self, x: int) -> int:
return self.value * x
# Validation + Ray compatibility!
worker = ValidatedRayWorker.options(mode="ray").init(name="test", value="10")
result = worker.compute("5").result() # Types coerced, result = 50
worker.stop()
**How Composition Wrapper Enables Ray Compatibility:**
When you use Worker + Typed or Worker + BaseModel, concurry automatically applies
a composition wrapper that solves the historical Ray serialization conflict.
The wrapper:
- Creates a plain Python class that holds the Typed/BaseModel instance internally
- Only exposes user-defined methods (infrastructure methods excluded)
- Delegates method calls to the wrapped instance
- Maintains full validation, type checking, and field constraints
- Has zero performance overhead (optimized delegation)
This happens transparently - no code changes needed! Your Typed/BaseModel workers
just work with Ray mode out of the box.
Different Execution Modes
# Synchronous (for testing/debugging)
worker = DataProcessor.options(mode="sync").init(2)
# Thread-based (good for I/O-bound tasks)
worker = DataProcessor.options(mode="thread").init(2)
# Process-based (good for CPU-bound tasks)
worker = DataProcessor.options(mode="process").init(2)
# Asyncio-based (good for async I/O)
worker = DataProcessor.options(mode="asyncio").init(2)
# Ray-based (distributed computing)
import ray
ray.init()
worker = DataProcessor.options(mode="ray", actor_options={"num_cpus": 1}).init(2)
Async Function Support
All workers can execute both sync and async functions. Async functions are automatically detected and executed correctly across all modes.
import asyncio
class AsyncWorker(Worker):
def __init__(self):
self.count = 0
async def async_method(self, x: int) -> int:
await asyncio.sleep(0.01) # Simulate async I/O
self.count += 1
return x * 2
def sync_method(self, x: int) -> int:
return x + 10
# Use asyncio mode for best async performance
worker = AsyncWorker.options(mode="asyncio").init()
result1 = worker.async_method(5).result() # 10
result2 = worker.sync_method(5).result() # 15
worker.stop()
# Submit async functions via TaskWorker
from concurry import TaskWorker
import asyncio
async def compute(x, y):
await asyncio.sleep(0.01)
return x ** 2 + y ** 2
task_worker = TaskWorker.options(mode="asyncio").init()
result = task_worker.submit(compute, 3, 4).result() # 25
task_worker.stop()
Performance: AsyncioWorkerProxy provides significant speedup (5-15x) for I/O-bound async operations by enabling true concurrent execution. Other modes execute async functions correctly but without concurrency benefits.
Blocking Mode
# Returns results directly instead of futures
worker = DataProcessor.options(mode="thread", blocking=True).init(5)
result = worker.process(10) # Returns 50 directly, not a future
worker.stop()
# With context manager (recommended)
with DataProcessor.options(mode="thread", blocking=True).init(5) as worker:
result = worker.process(10) # Returns 50 directly
# Worker automatically stopped
Submitting Arbitrary Functions with TaskWorker
# Use TaskWorker for Executor-like interface
from concurry import TaskWorker
def compute(x, y):
return x ** 2 + y ** 2
task_worker = TaskWorker.options(mode="process").init()
# Submit arbitrary functions
future = task_worker.submit(compute, 3, 4)
result = future.result() # 25
# Use map() for multiple tasks
results = list(task_worker.map(lambda x: x * 100, [1, 2, 3, 4, 5]))
task_worker.stop()
State Management
class Counter(Worker):
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
return self.count
# Each worker maintains its own state
with Counter.options(mode="thread").init() as worker1:
with Counter.options(mode="thread").init() as worker2:
print(worker1.increment().result()) # 1
print(worker1.increment().result()) # 2
print(worker2.increment().result()) # 1 (separate state)
# Both workers automatically stopped
Submission Queue (Client-Side Task Queuing):
Workers support client-side submission queuing via the max_queued_tasks parameter.
This prevents overloading worker backends when submitting large batches of tasks.
**Key Benefits:**
- Prevents memory exhaustion from thousands of pending futures
- Avoids backend overload (especially Ray actors)
- Reduces network saturation for distributed workers
- Works transparently with your submission loops
**How it works:**
The submission queue limits how many tasks can be "in-flight" (submitted but not completed)
per worker. When the queue is full, further submissions block until a task completes.
```python
# Create worker with submission queue
worker = MyWorker.options(
mode="thread",
max_queued_tasks=10 # Max 10 tasks in-flight
).init()
# Submit 1000 tasks - automatically blocks when queue is full
futures = [worker.process(item) for item in range(1000)]
results = gather(futures) # Submission queue prevents overload
worker.stop()
```
**Default values by mode:**
- sync/asyncio: None (bypassed) - immediate execution or event loop handles concurrency
- thread: 100 - high concurrency, large queue
- process: 5 - limited by CPU cores
- ray: 2 - minimize data transfer overhead
**Integration with other features:**
- **Limits**: Submission queue (client-side) + resource limits (worker-side) work together
- **Retries**: Only original submissions count, not retry attempts
- **Load Balancing**: Each worker in a pool has its own independent queue
- **On-Demand Workers**: Automatically bypass submission queue
For comprehensive documentation and examples, see the user guide:
`/docs/user-guide/limits.md#submission-queue`
Resource Protection with Limits
Workers support resource protection and rate limiting via the limits parameter.
Limits enable control over API rates, resource pools, and call frequency.
Important: Workers always have self.limits available, even when no limits
are configured. If no limits parameter is provided, workers get an empty
LimitSet that always allows acquisition without blocking. This means your
code can safely call self.limits.acquire() without checking if limits exist.
from concurry import Worker, LimitSet, RateLimit, CallLimit, ResourceLimit
from concurry import RateLimitAlgorithm
# Define limits
limits = LimitSet(limits=[
CallLimit(window_seconds=60, capacity=100), # 100 calls/min
RateLimit(
key="api_tokens",
window_seconds=60,
algorithm=RateLimitAlgorithm.TokenBucket,
capacity=1000
),
ResourceLimit(key="connections", capacity=10)
])
class APIWorker(Worker):
def __init__(self, api_key: str):
self.api_key = api_key
def call_api(self, prompt: str):
# Acquire limits before operation
# CallLimit automatically acquired with default of 1
with self.limits.acquire(requested={"api_tokens": 100}) as acq:
result = external_api_call(prompt)
# Update with actual usage
acq.update(usage={"api_tokens": result.tokens_used})
return result.response
# Option 1: Share limits across workers
worker1 = APIWorker.options(mode="thread", limits=limits).init("key1")
worker2 = APIWorker.options(mode="thread", limits=limits).init("key2")
# Both workers share the 1000 token/min pool
# Option 2: Private limits per worker
limit_defs = [
RateLimit(key="tokens", window_seconds=60, capacity=1000)
]
worker = APIWorker.options(mode="thread", limits=limit_defs).init("key")
# This worker has its own private 1000 token/min pool
# Option 3: No limits (always succeeds)
worker = APIWorker.options(mode="thread").init("key")
# self.limits.acquire() always succeeds immediately, no blocking
Limit Types:
- CallLimit: Count calls (usage always 1, no update needed)
- RateLimit: Token/bandwidth limiting (requires update() call)
- ResourceLimit: Semaphore-based resources (no update needed)
Key Behaviors:
- Passing LimitSet: Workers share the same limit pool
- Passing List[Limit]: Each worker gets private limits
- No limits parameter: Workers get empty LimitSet (always succeeds)
- CallLimit/ResourceLimit auto-acquired with default of 1
- RateLimits must be explicitly specified in requested dict
- RateLimits require update() call (raises RuntimeError if missing)
- Empty LimitSet has zero overhead (no synchronization, no waiting)
See user guide for more: /docs/user-guide/limits.md
Source code in src/concurry/core/worker/base_worker.py
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 | |
options(*, mode: Union[ExecutionMode, _NO_ARG_TYPE] = _NO_ARG, blocking: Union[bool, _NO_ARG_TYPE] = _NO_ARG, max_workers: Optional[Union[conint(ge=0), _NO_ARG_TYPE]] = _NO_ARG, load_balancing: Union[LoadBalancingAlgorithm, _NO_ARG_TYPE] = _NO_ARG, on_demand: Union[bool, _NO_ARG_TYPE] = _NO_ARG, max_queued_tasks: Optional[Union[conint(ge=0), _NO_ARG_TYPE]] = _NO_ARG, num_retries: Union[conint(ge=0), dict[str, conint(ge=0)], _NO_ARG_TYPE] = _NO_ARG, retry_on: Union[Any, dict[str, Any], _NO_ARG_TYPE] = _NO_ARG, retry_algorithm: Union[RetryAlgorithm, dict[str, RetryAlgorithm], _NO_ARG_TYPE] = _NO_ARG, retry_wait: Union[confloat(ge=0), dict[str, confloat(ge=0)], _NO_ARG_TYPE] = _NO_ARG, retry_jitter: Union[confloat(ge=0, le=1), dict[str, confloat(ge=0, le=1)], _NO_ARG_TYPE] = _NO_ARG, retry_until: Union[Any, dict[str, Any], _NO_ARG_TYPE] = _NO_ARG, **kwargs: Any) -> WorkerBuilder
classmethod
¶
Configure worker execution options.
Returns a WorkerBuilder that can be used to create worker instances with .init(args, *kwargs).
This method merges configuration from multiple sources in priority order: 1. Parameters passed to this method (highest priority) 2. @worker decorator parameters 3. class LLM(Worker, ...) inheritance parameters 4. global_config defaults (lowest priority)
Type Validation:
This method uses the @validate decorator from morphic, providing:
- Automatic type checking and conversion
- String-to-bool coercion (e.g., "true" → True)
- AutoEnum fuzzy matching for mode parameter
- Enhanced error messages for invalid inputs
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
Union[ExecutionMode, _NO_ARG_TYPE]
|
Execution mode (sync, thread, process, asyncio, ray) Accepts string or ExecutionMode enum value |
_NO_ARG
|
blocking
|
Union[bool, _NO_ARG_TYPE]
|
If True, method calls return results directly instead of futures
Accepts bool or string representation ("true", "false", "1", "0")
Default value determined by global_config. |
_NO_ARG
|
max_workers
|
Optional[Union[conint(ge=0), _NO_ARG_TYPE]]
|
Maximum number of workers in pool (optional)
- If None or 1: Creates single worker. If >1: Creates worker pool with specified size.
- Sync/Asyncio: Must be 1 or None (raises error otherwise)
- Default value determined by global_config. |
_NO_ARG
|
load_balancing
|
Union[LoadBalancingAlgorithm, _NO_ARG_TYPE]
|
Load balancing algorithm (optional)
- "round_robin": Distribute requests evenly
- "least_active": Select worker with fewest active calls
- "least_total": Select worker with fewest total calls
- "random": Random selection
- Default value determined by global_config. |
_NO_ARG
|
on_demand
|
Union[bool, _NO_ARG_TYPE]
|
If True, create workers on-demand per request (default: False) - Workers are created for each request and destroyed after completion - Useful for bursty workloads or resource-constrained environments - Cannot be used with Sync/Asyncio modes - With max_workers=0: Unlimited concurrent workers (Ray) or limited to cpu_count()-1 (Thread/Process) |
_NO_ARG
|
max_queued_tasks
|
Optional[Union[conint(ge=0), _NO_ARG_TYPE]]
|
Maximum number of in-flight tasks per worker (default varies by mode)
- Controls how many tasks can be submitted to a worker's backend before blocking
- Per-worker limit: each worker in a pool has its own independent queue
- Value of N means max N tasks submitted but not yet completed per worker
- Automatically bypassed in blocking mode (unlimited submissions allowed)
- Automatically bypassed in sync and asyncio modes
- Prevents overload when submitting large batches (e.g., 5000+ tasks to Ray)
- Default value determined by global_config. |
_NO_ARG
|
unwrap_futures
|
If True, automatically unwrap BaseFuture arguments
by calling .result() on them before passing to worker methods. This enables
seamless composition of workers. Set to False to pass futures as-is.
Default value determined by global_config. |
required | |
limits
|
Resource protection and rate limiting (optional, defaults to empty LimitSet) - Pass LimitSet: Workers share the same limit pool - Pass List[Limit]: Each worker gets private limits (creates shared LimitSet for pools) - Omit parameter: Workers get empty LimitSet (self.limits.acquire() always succeeds) Workers always have self.limits available, even when no limits configured. See Worker docstring "Resource Protection with Limits" section for details. |
required | |
num_retries
|
Union[conint(ge=0), dict[str, conint(ge=0)], _NO_ARG_TYPE]
|
Maximum number of retry attempts after initial failure
Total attempts = num_retries + 1 (initial attempt).
Set to 0 to disable retries (zero overhead).
Default value determined by global_config. |
_NO_ARG
|
retry_on
|
Union[Any, dict[str, Any], _NO_ARG_TYPE]
|
Exception types or callables that trigger retries (optional)
- Single exception class: retry_on=ValueError
- List of exceptions: retry_on=[ValueError, ConnectionError]
- Callable filter: retry_on=lambda exception, **ctx: "retry" in str(exception)
- Mixed list: retry_on=[ValueError, custom_filter]
Default value determined by global_config. |
_NO_ARG
|
retry_algorithm
|
Union[RetryAlgorithm, dict[str, RetryAlgorithm], _NO_ARG_TYPE]
|
Backoff strategy for wait times
Default value determined by global_config. |
_NO_ARG
|
retry_wait
|
Union[confloat(ge=0), dict[str, confloat(ge=0)], _NO_ARG_TYPE]
|
Minimum wait time between retries in seconds
Base wait time before applying strategy and jitter.
Default value determined by global_config. |
_NO_ARG
|
retry_jitter
|
Union[confloat(ge=0, le=1), dict[str, confloat(ge=0, le=1)], _NO_ARG_TYPE]
|
Jitter factor between 0 and 1
Uses Full Jitter algorithm from AWS: sleep = random(0, calculated_wait).
Set to 0 to disable jitter. Prevents thundering herd when many workers retry.
Default value determined by global_config. |
_NO_ARG
|
retry_until
|
Union[Any, dict[str, Any], _NO_ARG_TYPE]
|
Validation functions for output (optional)
- Single validator: retry_until=lambda result, **ctx: result.get("status") == "success"
- List of validators: retry_until=[validator1, validator2] (all must pass)
Validators receive result and context as kwargs. Return True for valid output.
If validation fails, triggers retry even without exception.
Useful for LLM output validation (JSON schema, XML format, etc.)
Default value determined by global_config. |
_NO_ARG
|
**kwargs
|
Any
|
Additional options passed to the worker implementation - For ray: num_cpus, num_gpus, resources, etc. - For process: mp_context (fork, spawn, forkserver) |
{}
|
Returns:
| Type | Description |
|---|---|
WorkerBuilder
|
A WorkerBuilder instance that can create workers via .init() |
Examples:
Basic Usage:
Type Coercion:
# String booleans are automatically converted
worker = MyWorker.options(mode="thread", blocking="true").init()
assert worker.blocking is True
Mode-Specific Options:
# Ray with resource requirements
worker = MyWorker.options(
mode="ray",
num_cpus=2,
num_gpus=1
).init(multiplier=3)
# Process with spawn context
worker = MyWorker.options(
mode="process",
mp_context="spawn"
).init(multiplier=3)
Future Unwrapping (Default Enabled):
# Automatic future unwrapping (default)
producer = Worker1.options(mode="thread").init()
consumer = Worker2.options(mode="thread").init()
future = producer.compute(10) # Returns BaseFuture
result = consumer.process(future).result() # future is auto-unwrapped
# Disable unwrapping to pass futures as objects
worker = MyWorker.options(mode="thread", unwrap_futures=False).init()
result = worker.inspect_future(future).result() # Receives BaseFuture object
Worker Pools:
# Create a thread pool with 10 workers
pool = MyWorker.options(mode="thread", max_workers=10).init(multiplier=3)
future = pool.process(10) # Dispatched to one of 10 workers
# Process pool with load balancing
pool = MyWorker.options(
mode="process",
max_workers=4,
load_balancing="least_active"
).init(multiplier=3)
# On-demand workers for bursty workloads
pool = MyWorker.options(
mode="ray",
on_demand=True,
max_workers=0 # Unlimited
).init(multiplier=3)
Retries:
# Basic retry with exponential backoff
worker = APIWorker.options(
mode="thread",
num_retries=3,
retry_algorithm="exponential",
retry_wait=1.0,
retry_jitter=0.3
).init()
# Retry only on specific exceptions
worker = APIWorker.options(
mode="thread",
num_retries=5,
retry_on=[ConnectionError, TimeoutError]
).init()
# Custom exception filter
worker = APIWorker.options(
mode="thread",
num_retries=3,
retry_on=lambda exception, **ctx: (
isinstance(exception, ValueError) and "retry" in str(exception)
)
).init()
# Output validation for LLM responses
worker = LLMWorker.options(
mode="thread",
num_retries=5,
retry_until=lambda result, **ctx: (
isinstance(result, dict) and "data" in result
)
).init()
# Multiple validators (all must pass)
worker = LLMWorker.options(
mode="thread",
num_retries=5,
retry_until=[
lambda result, **ctx: isinstance(result, str),
lambda result, **ctx: result.startswith("{"),
lambda result, **ctx: validate_json(result)
]
).init()
Per-Method Retry Configuration: All retry parameters support per-method configuration using dictionaries. This allows different retry settings for different worker methods.
```python
# Different retry settings per method
worker = APIWorker.options(
mode="thread",
num_retries={
"*": 0, # Default: no retries
"fetch_data": 3, # Moderate retries for fetch
"critical_op": 10 # Aggressive retries for critical
},
retry_wait={
"*": 1.0,
"critical_op": 3.0 # Longer wait for critical
},
retry_algorithm={
"*": RetryAlgorithm.Linear,
"critical_op": RetryAlgorithm.Exponential
}
).init()
# Dictionary format requires "*" key for default
# Keys are method names, values are the parameter values
# Methods not explicitly listed use the "*" default value
# Mix single values and dicts
worker = APIWorker.options(
mode="thread",
num_retries={"*": 0, "critical": 10}, # Per-method
retry_wait=2.0, # Single: all methods
retry_algorithm="exponential" # Single: all methods
).init()
# LLM worker with per-method validation
worker = LLMWorker.options(
mode="thread",
num_retries={"*": 0, "generate_json": 10, "generate_code": 15},
retry_until={
"*": None,
"generate_json": lambda result, **ctx: isinstance(result, dict),
"generate_code": lambda result, **ctx: is_valid_syntax(result)
}
).init()
# TaskWorker: use "submit" as method name
worker = TaskWorker.options(
mode="process",
num_retries={"*": 5, "submit": 3},
retry_on={"*": [Exception], "submit": [ConnectionError]}
).init()
```
Source code in src/concurry/core/worker/base_worker.py
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 | |
TaskWorker¶
concurry.core.worker.task_worker.TaskWorker
¶
Bases: Worker
A generic worker for submitting arbitrary tasks.
TaskWorker is a concrete worker implementation that provides an Executor-like interface for executing arbitrary functions in different execution contexts (sync, thread, process, asyncio, ray). Unlike custom workers that define specific methods, TaskWorker is designed for general-purpose task execution.
This class implements the same interface as concurrent.futures.Executor: - submit(fn, args, kwargs): Submit a single task - map(fn, iterables, **kwargs): Submit multiple tasks with automatic iteration
This class is intended to be used by higher-level abstractions like WorkerExecutor and WorkerPool, or directly when you don't need custom worker methods.
Examples:
Basic Task Execution:
from concurry import TaskWorker
# Create a task worker
worker = TaskWorker.options(mode="thread").init()
# Submit arbitrary functions
def compute(x, y):
return x ** 2 + y ** 2
future = worker.submit(compute, 3, 4)
result = future.result() # 25
worker.stop()
Using map() for Multiple Tasks:
worker = TaskWorker.options(mode="process").init()
def square(x):
return x ** 2
# Process multiple items
results = list(worker.map(square, range(10)))
print(results) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
worker.stop()
With Different Execution Modes:
# Thread-based execution
thread_worker = TaskWorker.options(mode="thread").init()
# Process-based execution for CPU-intensive tasks
process_worker = TaskWorker.options(mode="process").init()
# Asyncio-based execution
async_worker = TaskWorker.options(mode="asyncio").init()
# Submit tasks to any of them
result1 = thread_worker.submit(lambda x: x * 2, 10).result()
result2 = process_worker.submit(lambda x: x ** 3, 5).result()
result3 = async_worker.submit(lambda x: x + 100, 7).result()
thread_worker.stop()
process_worker.stop()
async_worker.stop()
Blocking Mode:
# Get results directly without futures
worker = TaskWorker.options(mode="thread", blocking=True).init()
result = worker.submit(lambda x: x * 10, 5) # Returns 50 directly
worker.stop()
Multiple Tasks with map():
worker = TaskWorker.options(mode="process").init()
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
# Process multiple inputs concurrently
results = list(worker.map(factorial, range(1, 11)))
print(results) # [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
worker.stop()
With Timeout:
import time
from concurry import TaskWorker
def slow_task(x):
time.sleep(1)
return x * 2
worker = TaskWorker.options(mode="thread").init()
# This will raise TimeoutError
try:
results = list(worker.map(slow_task, range(5), timeout=0.5))
except TimeoutError:
print("Task timed out!")
worker.stop()
With Bound Function:
from concurry import TaskWorker
def compute(x, y):
return x ** 2 + y ** 2
# Bind function during initialization
worker = TaskWorker.options(mode="thread").init(fn=compute)
# Submit without passing function
future = worker.submit(3, 4)
result = future.result() # 25
# Map without passing function
results = list(worker.map([(1, 2), (3, 4), (5, 6)]))
# Call directly
result = worker(3, 4).result() # 25
worker.stop()
With Progress Bar:
from concurry import TaskWorker
def square(x):
return x ** 2
worker = TaskWorker.options(mode="process").init(fn=square)
# Show progress bar during map
results = list(worker.map(range(100), progress=True))
# Custom progress bar configuration
results = list(worker.map(
range(100),
progress={"desc": "Processing", "ncols": 80}
))
worker.stop()
Source code in src/concurry/core/worker/task_worker.py
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 | |
Task Decorator¶
concurry.core.worker.task_decorator.task(*, mode: ExecutionMode, on_demand: Union[bool, _NO_ARG_TYPE] = _NO_ARG, **kwargs: Any) -> Callable
¶
Decorator to create a TaskWorker bound to a function.
This decorator transforms the decorated function into a TaskWorker instance.
The original function is bound to this worker.
Crucial Behavior:
1. The decorated symbol is no longer a function, but a TaskWorker instance.
2. Calling the decorated symbol invokes worker.submit(), returning a Future.
3. You must call .stop() on the decorated symbol to clean up resources.
4. All worker configuration (e.g., mode) is required here to initialize the worker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
ExecutionMode
|
Execution mode (sync, thread, process, asyncio, ray). Defaults to ExecutionMode.Sync |
required |
on_demand
|
Union[bool, _NO_ARG_TYPE]
|
Create workers on-demand. If not specified, uses global_config.defaults.task_decorator_on_demand (defaults to True). Note: on_demand is automatically set to False for Sync and Asyncio modes. |
_NO_ARG
|
**kwargs
|
Any
|
All other Worker.options() parameters are supported. |
{}
|
Returns:
| Type | Description |
|---|---|
Callable
|
Initialized TaskWorker instance bound to the decorated function |
Examples:
Basic Usage:
from concurry import task
# process_item becomes a TaskWorker instance
@task(mode="thread", max_workers=4)
def process_item(x):
return x ** 2
# Call like a function -> actually calls worker.submit()
future = process_item(10)
result = future.result() # 100
# Explicitly STOP the worker when done
process_item.stop()
With Limits:
from concurry import task, RateLimit
limits = [RateLimit(key="api", capacity=100, window_seconds=60)]
@task(mode="thread", limits=limits)
def call_api(prompt, limits): # limits param detected automatically
with limits.acquire(requested={"api": 1}):
return external_api(prompt)
result = call_api("Hello").result()
With Progress Bar:
@task(mode="process", max_workers=4)
def compute(x):
return x ** 2
results = list(compute.map(range(1000), progress=True))
Source code in src/concurry/core/worker/task_decorator.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | |