{"id":16644611,"url":"https://github.com/yeraydiazdiaz/futureproof","last_synced_at":"2025-09-20T20:32:17.377Z","repository":{"id":51270435,"uuid":"190892406","full_name":"yeraydiazdiaz/futureproof","owner":"yeraydiazdiaz","description":"Bulletproof concurrent.futures","archived":false,"fork":false,"pushed_at":"2022-05-01T14:56:59.000Z","size":111,"stargazers_count":52,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-01-11T18:52:44.676Z","etag":null,"topics":["concurrency","futures","threadpoolexecutor"],"latest_commit_sha":null,"homepage":"https://futureproof.readthedocs.io","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yeraydiazdiaz.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-06-08T13:42:10.000Z","updated_at":"2024-08-13T13:49:04.000Z","dependencies_parsed_at":"2022-08-27T21:25:10.687Z","dependency_job_id":null,"html_url":"https://github.com/yeraydiazdiaz/futureproof","commit_stats":null,"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yeraydiazdiaz%2Ffutureproof","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yeraydiazdiaz%2Ffutureproof/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yeraydiazdiaz%2Ffutureproof/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yeraydiazdiaz%2Ffutureproof/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yeraydiazdiaz","download_url":"https://codeload.github.com/yeraydiazdiaz/futureproof/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":233686443,"owners_count":18714143,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["concurrency","futures","threadpoolexecutor"],"created_at":"2024-10-12T08:11:53.363Z","updated_at":"2025-09-20T20:32:12.122Z","avatar_url":"https://github.com/yeraydiazdiaz.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Futureproof - Bulletproof concurrent.futures\n\n[![Documentation Status](https://readthedocs.org/projects/futureproof/badge/?version=latest)](https://futureproof.readthedocs.io/en/latest/?badge=latest)\n[![Build Status](https://github.com/yeraydiazdiaz/futureproof/workflows/CI/badge.svg?branch=master)](https://github.com/yeraydiazdiaz/futureproof/actions?workflow=CI)\n[![Supported Python Versions](https://img.shields.io/pypi/pyversions/futureproof.svg)](https://pypi.org/project/futureproof/)\n[![PyPI](https://img.shields.io/pypi/v/futureproof.svg)](https://pypi.org/project/futureproof/)\n[![codecov](https://codecov.io/gh/yeraydiazdiaz/futureproof/branch/master/graph/badge.svg)](https://codecov.io/gh/yeraydiazdiaz/futureproof)\n[![Read the Docs](https://img.shields.io/readthedocs/futureproof.svg)](http://futureproof.readthedocs.io/en/latest/)\n\n[`concurrent.futures`](https://docs.python.org/3/library/concurrent.futures.html) is amazing, but it's got some sharp edges that have bit me many times in the past.\n\nFutureproof is a thin wrapper around it addressing some of these problems and adding some\nusability features.\n\n## Features:\n\n- **Monitoring**: a summary of recent completed tasks is logged by default.\n- **Fail fast**: errors cause the main thread to raise an exception and stop by default.\n- **Error policy**: the user can decide whether to raise, log or completely ignore errors on tasks.\n- **Backpressure control**: large collections of tasks are consumed lazily as the executor completes tasks, drastically reducing memory consumption and improving responsiveness in these situations.\n\n## Current status: Alpha\n\nThe API is subject to change, any changes will be documented in the changelog.\n\nFutureproof was designed to wrap ThreadPoolExecutor, however version 0.2+ includes limited support ProcessPoolExecutor but only for Python3.7+.\n\n## concurrent.futures problems?\n\nLet's have a look at the canonical example for ThreadPoolExecutor:\n\n```python\nimport concurrent.futures\nimport urllib.request\n\nURLS = ['http://www.foxnews.com/',\n        'http://www.cnn.com/',\n        'http://europe.wsj.com/',\n        'http://www.bbc.co.uk/',\n        'http://some-made-up-domain-that-definitely-does-not-exist.com/']\n\n# Retrieve a single page and report the URL and contents\ndef load_url(url, timeout):\n    with urllib.request.urlopen(url, timeout=timeout) as conn:\n        return conn.read()\n\n# We can use a with statement to ensure threads are cleaned up promptly\nwith concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n    # Start the load operations and mark each future with its URL\n    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}\n    for future in concurrent.futures.as_completed(future_to_url):\n        url = future_to_url[future]\n        try:\n            data = future.result()\n        except Exception as exc:\n            print('%r generated an exception: %s' % (url, exc))\n        else:\n            print('%r page is %d bytes' % (url, len(data)))\n```\n\nJust to reiterate, this is amazing, the fact that the barrier of entry for multithreading is this small is really a testament to the great work done by Brian Quinlan and the core Python developers.\n\nHowever, I see two problems with this:\n\n1. The boilerplate. We need to enter a context manager, call `submit` manually keeping track of the futures and its arguments, call `as_completed` which actually returns an iterator, call `result` on the future remembering to handle the exception.\n2. It's surprising. Why do we need to get the result in order to raise? What if we don't expect it to raise? We probably want to know as soon as possible.\n\nIf you run this code you get the following output (at the time of this writing):\n\n```\n'http://some-made-up-domain-that-definitely-does-not-exist.com/' generated an exception: \u003curlopen error [Errno 8] nodename nor servname provided, or not known\u003e\n'http://www.foxnews.com/' page is 248838 bytes\n'http://www.bbc.co.uk/' page is 338658 bytes\n'http://www.cnn.com/' page is 991167 bytes\n'http://europe.wsj.com/' page is 970346 bytes\n```\n\nWhich is perfect. How does futureproof compare?\n\n```python\nexecutor = futureproof.FutureProofExecutor(max_workers=5)\nwith futureproof.TaskManager(executor) as tm:\n    for url in URLS:\n        tm.submit(load_url, url, 60)\n    for task in tm.as_completed():\n        print(\"%r page is %d bytes\" % (task.args[0], len(task.result)))\n```\n\nThat looks quite similar, there's an executor and a *task manager*. `submit` and `as_completed` are methods on it and there's no `try..except`. If we run it we get:\n\n```\n'http://www.foxnews.com/' page is 248838 bytes\nTraceback (most recent call last):\n  File \"/Users/yeray/.pyenv/versions/3.7.3/lib/python3.7/urllib/request.py\", line 1317, in do_open\n    encode_chunked=req.has_header('Transfer-encoding'))\n  ... omitted traceback output ...\nsocket.gaierror: [Errno 8] nodename nor servname provided, or not known\n```\n\nNotice that `futureproof` raised the exception immediately and everything stopped, as you would've expected in normal non-threaded Python, no surprises.\n\nIf we prefer `futureproof` gives you the option to log or even ignore exceptions using error policies. Say we want to log the exceptions:\n\n```python\nlogging.basicConfig(\n    level=logging.INFO,\n    format=\"[%(asctime)s %(thread)s] %(message)s\",\n    datefmt=\"%H:%M:%S\",\n)\n\nexecutor = futureproof.FutureProofExecutor(max_workers=5)\nwith futureproof.TaskManager(executor, error_policy=\"log\") as tm:\n    for url in URLS:\n        tm.submit(load_url, url, 60)\n\n    for task in tm.as_completed():\n        if not isinstance(task.result, Exception):\n            print(\"%r page is %d bytes\" % (task.args[0], len(task.result)))\n```\n\nNote we've added a check to only print the result in case it's not an exception, this outputs:\n\n```\n'http://www.foxnews.com/' page is 251088 bytes\n[12:09:15 4350641600] Task Task(fn=\u003cfunction load_url at 0x1029ef1e0\u003e, args=('http://some-made-up-domain-that-definitely-does-not-exist.com/', 60), kwargs={}, result=URLError(gaierror(8, 'nodename nor servname provided, or not known')),\n complete=True) raised an exception\nTraceback (most recent call last):\n  File \"/Users/yeray/.pyenv/versions/3.7.3/lib/python3.7/urllib/request.py\", line 1317, in do_open\n    encode_chunked=req.has_header('Transfer-encoding'))\n    ... omitted long traceback ...\n  File \"/Users/yeray/.pyenv/versions/3.7.3/lib/python3.7/urllib/request.py\", line 1319, in do_open\n    raise URLError(err)\nurllib.error.URLError: \u003curlopen error [Errno 8] nodename nor servname provided, or not known\u003e\n'http://some-made-up-domain-that-definitely-does-not-exist.com/' generated an exception: \u003curlopen error [Errno 8] nodename nor servname provided, or not known\u003e\n'http://www.bbc.co.uk/' page is 339087 bytes\n'http://www.cnn.com/' page is 991167 bytes\n[12:09:16 123145404444672] 5 task completed in the last 1.18 second(s)\n'http://europe.wsj.com/' page is 970880 bytes\n```\n\nNote we only had to configure logging and pass the appropriate error policy, everything else was taken care for us. You can also choose to ignore exceptions completely and manage them yourself accessing `result`, which is the workflow when using `concurrent.futures`.\n\n### `as_completed`?\n\nIf you think about it, why do we need `as_completed`?\n\nThe answer is for monitoring and error handling.\n\nIf we had loads of URLs, you don't want to wait until all URLs are back to show\noutput, it could take ages. But really it just adds complexity to the code.\nWhat does the example look like if you don't use `as_completed`?\n\n```python\nwith concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}\n\nfor future, url in future_to_url.items():\n    try:\n        data = future.result()\n    except Exception as exc:\n        print(\"%r generated an exception: %s\" % (url, exc))\n    else:\n        print(\"%r page is %d bytes\" % (url, len(data)))\n```\n\nWhich is arguably more readable, however, it has a subtle difference: there's\nno output until all the futures are complete. If you imagine tasks taking longer\nyou're left wondering if things are even working at all.\n\nLet's compare to the `futureproof` version:\n\n```python\nexecutor = futureproof.FutureProofExecutor(max_workers=5)\nwith futureproof.TaskManager(executor, error_policy=\"ignore\") as tm:\n    for url in URLS:\n        tm.submit(load_url, url, 60)\n\nfor task in tm.completed_tasks:\n    if isinstance(task.result, Exception):\n        print(\"%r generated an exception: %s\" % (task.args[0], task.result))\n    else:\n        print(\"%r page is %d bytes\" % (task.args[0], len(task.result)))\n```\n\n```\n[12:40:28 123145393414144] Starting executor monitor\n[12:40:29 123145393414144] 5 task completed in the last 1.01 second(s)\n[12:40:29 123145393414144] Shutting down monitor...\n'http://www.foxnews.com/' page is 252016 bytes\n'http://some-made-up-domain-that-definitely-does-not-exist.com/' generated an exception: \u003curlopen error [Errno 8] nodename nor servname provided, or not known\u003e\n'http://www.cnn.com/' page is 992648 bytes\n'http://www.bbc.co.uk/' page is 338987 bytes\n'http://europe.wsj.com/' page is 969285 bytes\n```\n\n`futureproof` defaults to logging monitoring information on the tasks so you\nalways know if things are working. Note how the task manager exposes\n`completed_tasks` allowing easy access to the results without having to manually\nkeep track of futures. Finally, as mentioned previously, you're also in total\ncontrol over exception handling so you don't need to add code for that either.\n\n## That's not _that_ big a deal..\n\nQuite, these are fairly minor problems that we can work around manually using\n`concurrent.futures`. But as you start to scale the number of jobs a more subtle\nissue creeps in.\n\nUnder the hood `concurrent.futures` uses queues to store the jobs, including\nthe function and its arguments. It does it right at the start, for _all_ the\njobs, which means that, in high job count situations, the queue grows very large\nand the main thread can hang and become unresponsive.\n\nA simple example:\n\n```python\ndef custom_sum(a, b):\n    time.sleep(0.1)\n    return a + b\n\n\nwith concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:\n    fn = partial(custom_sum, b=1)\n    ex.map(fn, range(1_000_000_000))\n```\n\nRunning this simple function with a billion times will result in the CPU maxing\nout and the memory usage will increase dramatically. Again, this all happens without\nany logging or output, and, to make things worse, a keyboard interrupt will not\nimmediately exit so you'll have to hit it repeatedly forcing the threads to exit\nin an unclean state.\n\nLet's compare this to `futureproof`:\n\n```python\n# same function as before\nex = futureproof.ThreadPoolExecutor(max_workers=2)\nwith futureproof.TaskManager(\n    ex, error_policy=futureproof.ErrorPolicyEnum.RAISE\n) as tm:\n    fn = partial(custom_sum, b=1)\n    tm.map(fn, range(1_000_000_000))\n```\n\nAlmost immediately you will see logging like:\n\n```\n[15:15:21 4632346048] Starting backpressure test with 1,000,000,000 tasks\n[15:15:21 4632346048] You may KeyboardInterrupt at any point and the executor will stop almost immediately\n[15:15:21 123145413025792] Starting executor monitor\n[15:15:22 123145413025792] 2 task completed in the last 0.20 second(s)\n[15:15:22 123145413025792] 1 task completed in the last 0.10 second(s)\n[15:15:22 123145413025792] 2 task completed in the last 0.21 second(s)\n...\n```\n\nAt any point a single keyboard interrupt will stop the process:\n\n```\n[15:15:24 123145413025792] 2 task completed in the last 0.20 second(s)\n^CTraceback (most recent call last):\n  File \"examples/backpressure.py\", line 64, in \u003cmodule\u003e\n    with_futureproof()\n  File \"examples/backpressure.py\", line 40, in with_futureproof\n    tm.map(fn, range(1_000_000_000))\n  File \"/Users/yeray/code/personal/futureproof/src/futureproof/task_manager.py\", line 65, in __exit__\n    self.run()\n  File \"/Users/yeray/code/personal/futureproof/src/futureproof/task_manager.py\", line 93, in run\n    for _ in self.as_completed():\n  File \"/Users/yeray/code/personal/futureproof/src/futureproof/task_manager.py\", line 104, in as_completed\n    yield self.wait_for_result()\n  File \"/Users/yeray/code/personal/futureproof/src/futureproof/task_manager.py\", line 146, in wait_for_result\n    completed_task = self._results_queue.get(block=True)\n  File \"/Users/yeray/.pyenv/versions/3.7.3/lib/python3.7/queue.py\", line 170, in get\n    self.not_empty.wait()\n  File \"/Users/yeray/.pyenv/versions/3.7.3/lib/python3.7/threading.py\", line 296, in wait\n    waiter.acquire()\nKeyboardInterrupt\n[15:15:24 123145413025792] 2 task completed in the last 0.20 second(s)\n[15:15:24 123145413025792] 1 task completed in the last 0.10 second(s)\n[15:15:24 123145413025792] Shutting down monitor...\n```\n\nCheck out the\n[examples directory](https://github.com/yeraydiazdiaz/futureproof/tree/master/examples/)\nfor complete examples between `futureproof` and `concurrent.futures` on all these\nscenarios, simply run `python examples/file.py` and append `futures` to run\nthe example using `concurrent.futures`.\n\n## Alternatives\n\nI am by no means the first person to address these problems. Here a few similar, more stable and feature full, albeit restrictively licensed alternatives:\n\n- [Pebble](https://pebble.readthedocs.io/en/latest/), LGPL 3.0\n- [more-executors](https://github.com/rohanpm/more-executors), GPL 3.0\n\n`futureproof` is licensed MIT.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyeraydiazdiaz%2Ffutureproof","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyeraydiazdiaz%2Ffutureproof","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyeraydiazdiaz%2Ffutureproof/lists"}