Futures API Reference¶
Complete API reference for Concurry's unified future interface.
Overview¶
All future classes in Concurry are implemented as frozen dataclasses for optimal performance and type safety:
- Performance: Optimized initialization (< 2.5 µs for
SyncFuture
) - Immutability: Frozen dataclasses prevent modification after creation
- Type Safety: Runtime validation in
__post_init__
ensures correct types - Thread Safety: Fast UUID generation using
os.urandom(16).hex()
All futures implement the complete concurrent.futures.Future
API with identical behavior across all backends.
Module: concurry.core.future
¶
Functions¶
wrap_future()¶
Wrap any future-like object in the unified Future interface.
This function automatically detects the type of future and wraps it in the appropriate BaseFuture subclass. It's the main entry point for using the unified future interface.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
future
|
Any
|
A future-like object from any execution framework. Supported types:
- |
required |
Returns:
Type | Description |
---|---|
BaseFuture
|
A BaseFuture instance providing the unified interface |
Example
from concurry.core.future import wrap_future
from concurrent.futures import ThreadPoolExecutor
import asyncio
# Works with threading futures
with ThreadPoolExecutor() as executor:
thread_future = executor.submit(lambda: 42)
unified = wrap_future(thread_future)
result = unified.result(timeout=5)
# Works with asyncio futures
async def async_example():
loop = asyncio.get_event_loop()
async_future = loop.create_future()
async_future.set_result(100)
unified = wrap_future(async_future)
result = unified.result(timeout=5)
return result
# Works with Ray (if installed)
import ray
ray.init()
@ray.remote
def remote_task(x):
return x ** 2
object_ref = remote_task.remote(42)
unified = wrap_future(object_ref)
result = unified.result(timeout=10)
ray.shutdown()
Note
If the input is already a BaseFuture, it's returned as-is without wrapping. This makes the function idempotent.
Source code in src/concurry/core/future.py
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 |
|
Classes¶
BaseFuture¶
Bases: ABC
Abstract base class providing a unified future interface.
This class serves as an abstraction layer that unifies different types of futures from various frameworks:
- Python's standard concurrent.futures.Future
- asyncio.Future
- Ray's ObjectRef
- Synchronous results (wrapped for API compatibility)
The API closely mirrors Python's concurrent.futures.Future
to ensure familiarity and compatibility.
Implementation:¶
BaseFuture and all its subclasses are implemented using slots for performance:
- High Performance: Optimized initialization with slots and fast UUID generation
- Memory Efficient: slots reduces memory overhead per instance
- Type Safety: Runtime validation at construction time with clear error messages
- Thread Safety: Fast UUID generation using
id(self)
(~0.01µs vs 2.5µs for os.urandom)
Each subclass defines slots and implements the abstract methods for their specific execution framework.
Key Benefits:¶
-
Framework Agnostic: Code can work with futures without needing to know their specific framework. The
wrap_future()
function automatically converts any future-like object into this unified interface. -
Consistent API: Provides a common interface (Adapter pattern) across all future types with:
__await__
support for async/await syntax- Consistent timeout and error handling
- Uniform callback mechanisms
-
Thread-Safe: All operations are thread-safe when a lock is provided. Implementations use locks to ensure thread-safety except for futures like SyncFuture that don't need it.
-
Extensible: New future types can be easily added by implementing this interface, allowing support for additional frameworks.
-
Type-Safe: Runtime validation at construction time with clear error messages for incorrect types.
Behavioral Guarantees:¶
All implementations of BaseFuture provide identical behavior through the public API:
- Exception Types: All futures raise the same exception types for the same conditions:
concurrent.futures.CancelledError
when accessing a cancelled futureTimeoutError
when operations exceed the specified timeout- Original exception from the computation when it fails
Note: Even asyncio.Future
raises concurrent.futures.CancelledError
(not asyncio.CancelledError
)
for API consistency.
-
Callbacks: All
add_done_callback()
implementations pass the wrapper future (not the underlying framework future) to the callback. Callbacks are called exactly once when the future completes. -
Cancellation:
cancel()
returns False if the future is already done, True if cancellation succeeded. Once cancelled,result()
andexception()
raiseCancelledError
. -
Blocking Behavior:
result()
andexception()
block until the future completes (unless a timeout is specified). Both methods respect the timeout parameter consistently. -
Await Support: All futures support async/await syntax through
__await__
, making them usable in async contexts regardless of the underlying framework.
Thread Safety:¶
All future operations are thread-safe. Each future maintains a private lock (_lock
) used to
synchronize access to internal state. SyncFuture sets this to None as it doesn't need locking.
Private Members:¶
Subclasses should define slots with these common attributes:
uuid
: Unique identifier for the future_result
: The computed result (or None if not yet available)_exception
: The exception raised (or None if successful)_done
: Whether the future has completed_cancelled
: Whether the future was cancelled_callbacks
: List of callbacks to invoke when done_lock
: Thread lock for synchronization (None for SyncFuture)
Framework-specific private members (like _future
, _loop
, _object_ref
) are defined only
on the subclasses that need them.
Source code in src/concurry/core/future.py
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 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
|
result(timeout: Optional[float] = None) -> Any
abstractmethod
¶
Get the result of the future, blocking if necessary.
This method blocks until the future completes or the timeout expires. Behavior is guaranteed to be identical across all future implementations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
timeout
|
Optional[float]
|
Maximum time to wait for result in seconds. None means wait indefinitely. |
None
|
Returns:
Type | Description |
---|---|
Any
|
The result of the computation |
Raises:
Type | Description |
---|---|
CancelledError
|
If the future was cancelled |
TimeoutError
|
If timeout is exceeded before completion |
Exception
|
Any exception raised by the underlying computation |
Source code in src/concurry/core/future.py
cancel() -> bool
abstractmethod
¶
Attempt to cancel the future.
If the call is currently being executed or finished running and cannot be cancelled, the method will return False. Otherwise, the call will be cancelled and the method will return True.
Returns:
Type | Description |
---|---|
bool
|
True if cancellation was successful, False otherwise |
Source code in src/concurry/core/future.py
cancelled() -> bool
abstractmethod
¶
Check if the future was cancelled.
Returns:
Type | Description |
---|---|
bool
|
True if the future was successfully cancelled |
done() -> bool
abstractmethod
¶
Check if the future is done (completed, cancelled, or failed).
Returns:
Type | Description |
---|---|
bool
|
True if the future is done (finished or was cancelled) |
exception(timeout: Optional[float] = None) -> Optional[Exception]
abstractmethod
¶
Get the exception raised by the computation, if any.
This method blocks until the future completes or the timeout expires. Behavior is guaranteed to be identical across all future implementations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
timeout
|
Optional[float]
|
Maximum time to wait for completion in seconds. None means wait indefinitely. |
None
|
Returns:
Type | Description |
---|---|
Optional[Exception]
|
The exception raised by the computation, or None if it succeeded |
Raises:
Type | Description |
---|---|
CancelledError
|
If the future was cancelled |
TimeoutError
|
If timeout is exceeded before completion |
Source code in src/concurry/core/future.py
add_done_callback(fn: Callable) -> None
abstractmethod
¶
Add a callback to be called when the future completes.
The callback receives the wrapper future (this BaseFuture instance), not the underlying framework future. This ensures consistent behavior across all implementations.
If the future is already done, the callback is called immediately (in the same thread). Otherwise, it's called when the future completes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fn
|
Callable
|
Callback function that takes the future (BaseFuture) as its single argument |
required |
Source code in src/concurry/core/future.py
SyncFuture¶
Bases: BaseFuture
Future implementation for synchronous execution.
This future type represents a computation that has already completed. It's useful for wrapping immediate results in the unified future interface.
Implementation:¶
SyncFuture is implemented as a highly optimized slots-based class:
- Performance: Initializes in < 0.5 microseconds
- Thread-Safe: No lock needed; single-threaded usage model provides thread-safety
- Type-Safe: Validates
exception_value
is an Exception or None at construction - Always Done: Created with
_done=True
since the result is immediately available - Fast UUID: Uses
id(self)
for instant unique identification
Parameters:
Name | Type | Description | Default |
---|---|---|---|
result_value
|
Any
|
The result value (default: None) |
None
|
exception_value
|
Optional[Exception]
|
An exception that was raised (default: None). Must be an Exception instance or None. |
None
|
Raises:
Type | Description |
---|---|
TypeError
|
If exception_value is not None and not an Exception instance |
Example
# Create a future with a result
future = SyncFuture(result_value=42)
print(future.result()) # 42
# Create a future with an exception
future = SyncFuture(exception_value=ValueError("Error"))
try:
future.result()
except ValueError as e:
print(f"Got error: {e}")
# Type validation at construction
try:
future = SyncFuture(exception_value="not an exception")
except TypeError as e:
print(f"TypeError: {e}") # exception_value must be an Exception or None
Source code in src/concurry/core/future.py
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
|
result(timeout: Optional[float] = None) -> Any
¶
Get the result, raising exceptions if present.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
timeout
|
Optional[float]
|
Ignored for SyncFuture (always immediate) |
None
|
Returns:
Type | Description |
---|---|
Any
|
The result value |
Raises:
Type | Description |
---|---|
CancelledError
|
If the future was cancelled |
Exception
|
Any exception from the computation |
Source code in src/concurry/core/future.py
cancel() -> bool
¶
Attempt to cancel the future.
Returns:
Name | Type | Description |
---|---|---|
False |
bool
|
SyncFuture cannot be cancelled (already done) |
cancelled() -> bool
¶
running() -> bool
¶
Check if the future is currently running.
Returns:
Name | Type | Description |
---|---|---|
False |
bool
|
SyncFuture is never in a running state |
done() -> bool
¶
Check if the future is done.
Returns:
Name | Type | Description |
---|---|---|
True |
bool
|
SyncFuture is always done at creation |
exception(timeout: Optional[float] = None) -> Optional[Exception]
¶
Get the exception if one was raised.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
timeout
|
Optional[float]
|
Ignored for SyncFuture (always immediate) |
None
|
Returns:
Type | Description |
---|---|
Optional[Exception]
|
The exception or None |
Raises:
Type | Description |
---|---|
CancelledError
|
If the future was cancelled |
Source code in src/concurry/core/future.py
add_done_callback(fn: Callable) -> None
¶
Add a callback to be called when the future completes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fn
|
Callable
|
Callback function that takes the future as its argument |
required |
Note
Since SyncFuture is always done, the callback is called immediately.
Source code in src/concurry/core/future.py
ConcurrentFuture¶
Bases: BaseFuture
Wrapper for concurrent.futures.Future to provide unified interface.
This wrapper provides a consistent API for futures from Python's standard
concurrent.futures
module (ThreadPoolExecutor, ProcessPoolExecutor).
Implementation:¶
ConcurrentFuture is an optimized slots-based wrapper for concurrent.futures.Future
:
- Performance: Fast UUID generation using
id(self)
(~0.01µs vs 2.5µs) - Thread-Safe: Delegates to the inherently thread-safe
concurrent.futures.Future
- Type-Safe: Validates the wrapped future is a
concurrent.futures.Future
at construction - Zero Overhead: Direct delegation to underlying future methods
- API Compatible: Matches
concurrent.futures.Future
exactly
Parameters:
Name | Type | Description | Default |
---|---|---|---|
future
|
Future
|
A |
required |
Raises:
Type | Description |
---|---|
TypeError
|
If future is not a |
Example
from concurrent.futures import ThreadPoolExecutor
from concurry.core.future import ConcurrentFuture
with ThreadPoolExecutor() as executor:
py_future = executor.submit(lambda: 42)
future = ConcurrentFuture(future=py_future)
result = future.result(timeout=5)
# Type validation at construction
try:
future = ConcurrentFuture(future="not a future")
except TypeError as e:
print(f"TypeError: {e}") # future must be a concurrent.futures.Future
Source code in src/concurry/core/future.py
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 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 |
|
result(timeout: Optional[float] = None) -> Any
¶
Get the result of the future.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
timeout
|
Optional[float]
|
Maximum time to wait for result in seconds |
None
|
Returns:
Type | Description |
---|---|
Any
|
The result of the computation |
Raises:
Type | Description |
---|---|
CancelledError
|
If the future was cancelled |
TimeoutError
|
If timeout is exceeded |
Exception
|
Any exception from the computation |
Source code in src/concurry/core/future.py
cancel() -> bool
¶
Attempt to cancel the future.
Returns:
Type | Description |
---|---|
bool
|
True if cancellation succeeded, False otherwise |
cancelled() -> bool
¶
Check if the future was cancelled.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
Cancellation status |
running() -> bool
¶
Check if the future is currently being executed.
Returns:
Type | Description |
---|---|
bool
|
True if the future is currently being executed |
done() -> bool
¶
Check if the future is done.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
Completion status |
exception(timeout: Optional[float] = None) -> Optional[Exception]
¶
Get the exception if one was raised.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
timeout
|
Optional[float]
|
Maximum time to wait for completion in seconds |
None
|
Returns:
Type | Description |
---|---|
Optional[Exception]
|
The exception or None |
Raises:
Type | Description |
---|---|
CancelledError
|
If the future was cancelled |
TimeoutError
|
If timeout is exceeded |
Source code in src/concurry/core/future.py
add_done_callback(fn: Callable) -> None
¶
Add a callback to be called when the future completes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fn
|
Callable
|
Callback function that takes the future as its argument |
required |
Source code in src/concurry/core/future.py
AsyncioFuture¶
Bases: BaseFuture
Wrapper for asyncio Future to provide unified interface.
This wrapper provides a consistent API for asyncio futures, including support for timeout parameters that aren't available in the native asyncio API.
Implementation:¶
AsyncioFuture is an optimized slots-based wrapper for asyncio.Future
:
- Performance: Fast UUID generation using
id(self)
(~0.01µs) - Thread-Safe: Uses an internal lock for thread-safe access to asyncio futures
- Type-Safe: Validates the wrapped future is an
asyncio.Future
at construction - Timeout Support: Adds timeout parameters to
result()
andexception()
methods - Exception Conversion: Converts
asyncio.CancelledError
toconcurrent.futures.CancelledError
for API consistency
Parameters:
Name | Type | Description | Default |
---|---|---|---|
future
|
Any
|
An |
required |
Raises:
Type | Description |
---|---|
TypeError
|
If future is not an |
Example
import asyncio
from concurry.core.future import AsyncioFuture
async def example():
loop = asyncio.get_event_loop()
async_future = loop.create_future()
future = AsyncioFuture(future=async_future)
# Set result
async_future.set_result(42)
# Get result with timeout (not available in native asyncio!)
result = future.result(timeout=5)
return result
# Type validation at construction
try:
future = AsyncioFuture(future="not an asyncio future")
except TypeError as e:
print(f"TypeError: {e}") # future must be an asyncio.Future
# Exception conversion for API consistency
async def test_cancellation():
loop = asyncio.get_event_loop()
async_future = loop.create_future()
future = AsyncioFuture(future=async_future)
async_future.cancel()
try:
future.result()
except concurrent.futures.CancelledError:
print("Raises concurrent.futures.CancelledError, not asyncio.CancelledError!")
Source code in src/concurry/core/future.py
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 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 |
|
result(timeout: Optional[float] = None) -> Any
¶
Get the result of the future.
This method uses polling to wait for the asyncio.Future to complete. Note: This is less efficient than concurrent.futures.Future blocking. For better performance in worker proxies, use ConcurrentFuture instead.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
timeout
|
Optional[float]
|
Maximum time to wait for result in seconds |
None
|
Returns:
Type | Description |
---|---|
Any
|
The result of the computation |
Raises:
Type | Description |
---|---|
CancelledError
|
If the future was cancelled |
TimeoutError
|
If timeout is exceeded |
Exception
|
Any exception from the computation |
Source code in src/concurry/core/future.py
running() -> bool
¶
Check if the future is currently being executed.
Note: asyncio.Future doesn't have a running() method, so we consider it running if it's neither done nor cancelled.
Returns:
Type | Description |
---|---|
bool
|
True if the future is currently being executed |
Source code in src/concurry/core/future.py
RayFuture¶
Bases: BaseFuture
Wrapper for Ray ObjectRef to provide unified interface.
This wrapper provides a consistent API for Ray's ObjectRef, which is returned when submitting tasks to Ray. Requires Ray is installed.
Implementation:¶
RayFuture is an optimized slots-based wrapper for Ray's ObjectRef
:
- Performance: Fast UUID generation using
id(self)
(~0.01µs) - Thread-Safe: Uses an internal lock to ensure thread-safe state management
- Type-Safe: Validates the wrapped object_ref is a Ray
ObjectRef
at construction - Exception Conversion: Converts Ray's
GetTimeoutError
to standardTimeoutError
- Callback Support: Implements proper callback invocation on completion
- State Tracking: Maintains internal state for completion, cancellation, and results
Parameters:
Name | Type | Description | Default |
---|---|---|---|
object_ref
|
Any
|
A Ray |
required |
Raises:
Type | Description |
---|---|
TypeError
|
If object_ref is not a Ray |
Example
import ray
from concurry.core.future import RayFuture
ray.init()
@ray.remote
def compute(x):
return x ** 2
# Ray returns an ObjectRef
object_ref = compute.remote(42)
# Wrap in unified interface
future = RayFuture(object_ref=object_ref)
result = future.result(timeout=10)
ray.shutdown()
# Type validation at construction
try:
future = RayFuture(object_ref="not an object ref")
except TypeError as e:
print(f"TypeError: {e}") # object_ref must be a Ray ObjectRef
Note
This class is only available when Ray is installed.
Install with: pip install concurry[ray]
Source code in src/concurry/core/future.py
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 |
|
result(timeout: Optional[float] = None) -> Any
¶
Get the result of the future.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
timeout
|
Optional[float]
|
Maximum time to wait for result in seconds |
None
|
Returns:
Type | Description |
---|---|
Any
|
The result of the computation |
Raises:
Type | Description |
---|---|
CancelledError
|
If the future was cancelled |
TimeoutError
|
If timeout is exceeded |
Exception
|
Any exception from the computation |
Source code in src/concurry/core/future.py
cancel() -> bool
¶
Attempt to cancel the future.
Returns:
Type | Description |
---|---|
bool
|
True if cancellation succeeded, False otherwise |
Source code in src/concurry/core/future.py
cancelled() -> bool
¶
Check if the future was cancelled.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
Cancellation status |
running() -> bool
¶
Check if the future is currently being executed.
Returns:
Type | Description |
---|---|
bool
|
True if the future is currently being executed (not done and not cancelled) |
Source code in src/concurry/core/future.py
done() -> bool
¶
Check if the future is done.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
Completion status |
Source code in src/concurry/core/future.py
exception(timeout: Optional[float] = None) -> Optional[Exception]
¶
Get the exception if one was raised.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
timeout
|
Optional[float]
|
Maximum time to wait for completion in seconds |
None
|
Returns:
Type | Description |
---|---|
Optional[Exception]
|
The exception or None |
Raises:
Type | Description |
---|---|
CancelledError
|
If the future was cancelled |
TimeoutError
|
If timeout is exceeded |
Source code in src/concurry/core/future.py
add_done_callback(fn: Callable) -> None
¶
Add a callback to be called when the future completes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fn
|
Callable
|
Callback function that takes the future as its argument |
required |
Source code in src/concurry/core/future.py
Ray Required
This class is only available when Ray is installed: pip install concurry[ray]
Usage Examples¶
Basic Usage¶
from concurry.core.future import wrap_future
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor() as executor:
# Submit a task
future = executor.submit(lambda x: x ** 2, 42)
# Wrap in unified interface
unified = wrap_future(future)
# Use consistent API
result = unified.result(timeout=5)
print(f"Result: {result}")
Async/Await Support¶
from concurry.core.future import wrap_future
from concurrent.futures import ThreadPoolExecutor
import asyncio
async def async_example():
with ThreadPoolExecutor() as executor:
future = wrap_future(executor.submit(lambda: 42))
# Use await syntax
result = await future
print(f"Result: {result}")
asyncio.run(async_example())
Error Handling¶
from concurry.core.future import wrap_future
future = wrap_future(some_future)
try:
result = future.result(timeout=10)
except TimeoutError:
print("Operation timed out")
future.cancel()
except Exception as e:
print(f"Task failed: {e}")
Callbacks¶
from concurry.core.future import wrap_future, BaseFuture
def on_complete(future: BaseFuture):
try:
result = future.result()
print(f"Task completed: {result}")
except Exception as e:
print(f"Task failed: {e}")
future = wrap_future(some_future)
future.add_done_callback(on_complete)
Type Signatures¶
BaseFuture Methods¶
from concurry.core.future import BaseFuture
from typing import Any, Callable, Optional
class BaseFuture:
def result(self, timeout: Optional[float] = None) -> Any:
"""Get the result, blocking if necessary."""
...
def cancel(self) -> bool:
"""Attempt to cancel the future."""
...
def cancelled(self) -> bool:
"""Check if the future was cancelled."""
...
def done(self) -> bool:
"""Check if the future is done."""
...
def exception(self, timeout: Optional[float] = None) -> Optional[Exception]:
"""Get the exception raised, if any."""
...
def add_done_callback(self, fn: Callable[[BaseFuture], None]) -> None:
"""Add a callback to be called when complete."""
...
def __await__(self):
"""Make the future awaitable."""
...
wrap_future Function¶
from concurry.core.future import BaseFuture, wrap_future
from typing import Any
def wrap_future(future: Any) -> BaseFuture:
"""
Wrap any future-like object in the unified interface.
Args:
future: A future-like object from any framework
Returns:
A BaseFuture instance providing the unified interface
"""
...
See Also¶
- Futures User Guide - Learn how to use futures
- Examples - See practical examples
- Progress API - Progress bar API reference