Run multiple functions in parallel and return results in the same order as calls. Equivalent to Promise.all in JS. Example usage: results = parallel_function_calls([ (func1, (arg1, arg2)), (func2, (arg3, arg4)), ])
(function_list: List[Tuple[Callable[..., Any], Tuple[Any, ...]]])
| 486 | |
| 487 | |
| 488 | def parallel_function_calls(function_list: List[Tuple[Callable[..., Any], Tuple[Any, ...]]]) -> List[Any]: |
| 489 | """ |
| 490 | Run multiple functions in parallel and return results in the same order as calls. Equivalent to Promise.all in JS. |
| 491 | |
| 492 | Example usage: |
| 493 | |
| 494 | results = parallel_function_calls([ |
| 495 | (func1, (arg1, arg2)), |
| 496 | (func2, (arg3, arg4)), |
| 497 | ]) |
| 498 | """ |
| 499 | results = [None] * len(function_list) |
| 500 | exceptions = [] |
| 501 | |
| 502 | def worker(index, func, args): |
| 503 | try: |
| 504 | result = func(*args) |
| 505 | results[index] = result |
| 506 | except Exception as e: |
| 507 | exceptions.append((index, str(e))) |
| 508 | |
| 509 | with ThreadPoolExecutor() as executor: |
| 510 | futures = [] |
| 511 | for i, (func, args) in enumerate(function_list): |
| 512 | future = executor.submit(worker, i, func, args) |
| 513 | futures.append(future) |
| 514 | |
| 515 | # Wait for all futures to complete |
| 516 | for future in as_completed(futures): |
| 517 | pass |
| 518 | |
| 519 | # Check if there were any exceptions |
| 520 | if exceptions: |
| 521 | print("Exceptions occurred:") |
| 522 | for index, error in exceptions: |
| 523 | print(f"Function at index {index}: {error}") |
| 524 | |
| 525 | return results |
| 526 | |
| 527 | |
| 528 | def match_regex(regex: str, text: str) -> bool: |