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, ...]]])
| 600 | |
| 601 | |
| 602 | def parallel_function_calls(function_list: List[Tuple[Callable[..., Any], Tuple[Any, ...]]]) -> List[Any]: |
| 603 | """ |
| 604 | Run multiple functions in parallel and return results in the same order as calls. Equivalent to Promise.all in JS. |
| 605 | |
| 606 | Example usage: |
| 607 | |
| 608 | results = parallel_function_calls([ |
| 609 | (func1, (arg1, arg2)), |
| 610 | (func2, (arg3, arg4)), |
| 611 | ]) |
| 612 | """ |
| 613 | results = [None] * len(function_list) |
| 614 | exceptions = [] |
| 615 | |
| 616 | def worker(index, func, args): |
| 617 | try: |
| 618 | result = func(*args) |
| 619 | results[index] = result |
| 620 | except Exception as e: |
| 621 | exceptions.append((index, str(e))) |
| 622 | |
| 623 | with ThreadPoolExecutor() as executor: |
| 624 | futures = [] |
| 625 | for i, (func, args) in enumerate(function_list): |
| 626 | future = executor.submit(worker, i, func, args) |
| 627 | futures.append(future) |
| 628 | |
| 629 | # Wait for all futures to complete |
| 630 | for future in as_completed(futures): |
| 631 | pass |
| 632 | |
| 633 | # Check if there were any exceptions |
| 634 | if exceptions: |
| 635 | print("Exceptions occurred:") |
| 636 | for index, error in exceptions: |
| 637 | print(f"Function at index {index}: {error}") |
| 638 | |
| 639 | return results |
| 640 | |
| 641 | |
| 642 | def match_regex(regex: str, text: str) -> bool: |