futured


Namefutured JSON
Version 1.5 PyPI version JSON
download
home_pageNone
SummaryFunctional interface for concurrent futures, including async coroutines.
upload_time2024-06-02 23:23:02
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseCopyright 2022 Aric Coady Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
keywords concurrent futures threads processes async asyncio
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![image](https://img.shields.io/pypi/v/futured.svg)](https://pypi.org/project/futured/)
![image](https://img.shields.io/pypi/pyversions/futured.svg)
[![image](https://pepy.tech/badge/futured)](https://pepy.tech/project/futured)
![image](https://img.shields.io/pypi/status/futured.svg)
[![image](https://github.com/coady/futured/workflows/build/badge.svg)](https://github.com/coady/futured/actions)
[![image](https://codecov.io/gh/coady/futured/branch/main/graph/badge.svg)](https://codecov.io/github/coady/futured)
[![image](https://github.com/coady/futured/workflows/codeql/badge.svg)](https://github.com/coady/futured/security/code-scanning)
[![image](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![image](https://mypy-lang.org/static/mypy_badge.svg)](https://mypy-lang.org/)

Futured provides a consistent interface for concurrent functional programming in Python. It wraps any callable to return a `concurrent.futures.Future`, wraps any async coroutine with a compatible `Task` interface, and provides concurrent iterators and context managers for futures.

## Usage
### threaded, processed
Transform any callable into one which runs in a thread or process pool, and returns a future.

```python
from futured import threaded, processed
import httpx

fetch = threaded(httpx.Client().get)
fetch(url)  # return Future

fs = (fetch(url + path) for path in paths)
threaded.results(fs)  # generate results from futures
threaded.results(fs, timeout=...)  # generate results as completed

fetch.map(urls)  # generate results in order
fetch.map(urls, timeout=...)  # generate results as completed
fetch.mapzip(urls)  # generate (url, result) pairs as completed
```

Thread and process pool executors may be used as context managers, customized with options, and reused with different callables.

```python
threaded(max_workers=...)(func, ...)
processed(max_workers=...)(func, ...)
```

`futured` classes have a `waiting` context manager which collects results from tasks. Futures can be registered at creation, or appended to the list of tasks.

```python
with threaded.waiting(*fs) as tasks:
    tasks.append(future)
tasks  # list of completed results
```

`futured` classes provide a `tasks` interface which generalizes `futures.as_completed` and `futures.wait`, while allowing the set of tasks to be modified, e.g., for retries.

```python
threaded.tasks(fs, timeout=...)  # mutable set of running tasks which iterate as completed
```

### asynced
The same interface works for `asyncio`.

```python
from futured import asynced
import httpx

fetch = asynced(httpx.AsyncClient().get)
fetch(url)  # return coroutine

asynced.results(fs)  # generate results from futures
asynced.results(fs, timeout=...)  # generate results as completed

fetch.map(urls)  # generate results in order
fetch.map(urls, timeout=...)  # generate results as completed
fetch.mapzip(urls)  # generate (url, result) pairs as completed
```

`asynced` provides utilities for calling coroutines from a synchronous context. `waiting` is similar to [trio's nursery](https://trio.readthedocs.io/en/latest/reference-core.html#nurseries-and-spawning), but returns results from a synchronous `with` block.

```python
asynced.run(async_func, ...)  # call and run until complete
asynced.run(async_gen, ...)  # call and run synchronous iterator
with asynced.waiting(*fs) as tasks:  # concurrent coroutines completed in a block
asynced.tasks(fs, timeout=...)  # mutable set of running tasks which iterate as completed
```

### extensions
There is also support for [dask distributed](https://distributed.dask.org/) clients and [gevent](http://www.gevent.org/) greenlets.

```python
from futured import distributed, greened
```

### decorators
Naturally `futured` wrappers can be used as decorators, but arguments can also be partially bound.

```python
@threaded
def slow():
   ...

fetch = threaded(httpx.Client().get, url)
fetch(params=...)
```

Methods are supported, as well as a `decorated` utility for automatically subclassing.

```python
from futured import decorated

FutureClient = decorated(httpx.Client, request=threaded)

 # equivalent to
class FutureClient(httpx.Client):
    request = threaded(httpx.Client.request)
```

### command
`command` wraps `subprocess.Popen` to provide a `Future` compatible interface.

```python
from futured import futured, command

command('ls').result()  # return stdout or raises stderr
command('ls').pipe('wc')  # pipes into next command, or | ('wc',... )
for line in command('ls'):  # iterable lines
command.coroutine('ls')  # return coroutine

futured(command, 'ls')  # supports `map` interface
asynced(command.coroutine, 'ls')  # supports `map` interface with timeout
```

### forked
`forked` allows iteration in separate child processes.

```python
from futured import forked

for value in forked(values, max_workers=...):
    # in a child process
 # in parent after children have exited
```

## Installation
```console
% pip install futured
```

## Tests
100% branch coverage.

```console
% pytest [--cov]
```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "futured",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "concurrent, futures, threads, processes, async, asyncio",
    "author": null,
    "author_email": "Aric Coady <aric.coady@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/ab/4c/3fb3df57b2670e433197c8706347c260cb2a1df5c22917a4e6d9559b4b88/futured-1.5.tar.gz",
    "platform": null,
    "description": "[![image](https://img.shields.io/pypi/v/futured.svg)](https://pypi.org/project/futured/)\n![image](https://img.shields.io/pypi/pyversions/futured.svg)\n[![image](https://pepy.tech/badge/futured)](https://pepy.tech/project/futured)\n![image](https://img.shields.io/pypi/status/futured.svg)\n[![image](https://github.com/coady/futured/workflows/build/badge.svg)](https://github.com/coady/futured/actions)\n[![image](https://codecov.io/gh/coady/futured/branch/main/graph/badge.svg)](https://codecov.io/github/coady/futured)\n[![image](https://github.com/coady/futured/workflows/codeql/badge.svg)](https://github.com/coady/futured/security/code-scanning)\n[![image](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)\n[![image](https://mypy-lang.org/static/mypy_badge.svg)](https://mypy-lang.org/)\n\nFutured provides a consistent interface for concurrent functional programming in Python. It wraps any callable to return a `concurrent.futures.Future`, wraps any async coroutine with a compatible `Task` interface, and provides concurrent iterators and context managers for futures.\n\n## Usage\n### threaded, processed\nTransform any callable into one which runs in a thread or process pool, and returns a future.\n\n```python\nfrom futured import threaded, processed\nimport httpx\n\nfetch = threaded(httpx.Client().get)\nfetch(url)  # return Future\n\nfs = (fetch(url + path) for path in paths)\nthreaded.results(fs)  # generate results from futures\nthreaded.results(fs, timeout=...)  # generate results as completed\n\nfetch.map(urls)  # generate results in order\nfetch.map(urls, timeout=...)  # generate results as completed\nfetch.mapzip(urls)  # generate (url, result) pairs as completed\n```\n\nThread and process pool executors may be used as context managers, customized with options, and reused with different callables.\n\n```python\nthreaded(max_workers=...)(func, ...)\nprocessed(max_workers=...)(func, ...)\n```\n\n`futured` classes have a `waiting` context manager which collects results from tasks. Futures can be registered at creation, or appended to the list of tasks.\n\n```python\nwith threaded.waiting(*fs) as tasks:\n    tasks.append(future)\ntasks  # list of completed results\n```\n\n`futured` classes provide a `tasks` interface which generalizes `futures.as_completed` and `futures.wait`, while allowing the set of tasks to be modified, e.g., for retries.\n\n```python\nthreaded.tasks(fs, timeout=...)  # mutable set of running tasks which iterate as completed\n```\n\n### asynced\nThe same interface works for `asyncio`.\n\n```python\nfrom futured import asynced\nimport httpx\n\nfetch = asynced(httpx.AsyncClient().get)\nfetch(url)  # return coroutine\n\nasynced.results(fs)  # generate results from futures\nasynced.results(fs, timeout=...)  # generate results as completed\n\nfetch.map(urls)  # generate results in order\nfetch.map(urls, timeout=...)  # generate results as completed\nfetch.mapzip(urls)  # generate (url, result) pairs as completed\n```\n\n`asynced` provides utilities for calling coroutines from a synchronous context. `waiting` is similar to [trio's nursery](https://trio.readthedocs.io/en/latest/reference-core.html#nurseries-and-spawning), but returns results from a synchronous `with` block.\n\n```python\nasynced.run(async_func, ...)  # call and run until complete\nasynced.run(async_gen, ...)  # call and run synchronous iterator\nwith asynced.waiting(*fs) as tasks:  # concurrent coroutines completed in a block\nasynced.tasks(fs, timeout=...)  # mutable set of running tasks which iterate as completed\n```\n\n### extensions\nThere is also support for [dask distributed](https://distributed.dask.org/) clients and [gevent](http://www.gevent.org/) greenlets.\n\n```python\nfrom futured import distributed, greened\n```\n\n### decorators\nNaturally `futured` wrappers can be used as decorators, but arguments can also be partially bound.\n\n```python\n@threaded\ndef slow():\n   ...\n\nfetch = threaded(httpx.Client().get, url)\nfetch(params=...)\n```\n\nMethods are supported, as well as a `decorated` utility for automatically subclassing.\n\n```python\nfrom futured import decorated\n\nFutureClient = decorated(httpx.Client, request=threaded)\n\n # equivalent to\nclass FutureClient(httpx.Client):\n    request = threaded(httpx.Client.request)\n```\n\n### command\n`command` wraps `subprocess.Popen` to provide a `Future` compatible interface.\n\n```python\nfrom futured import futured, command\n\ncommand('ls').result()  # return stdout or raises stderr\ncommand('ls').pipe('wc')  # pipes into next command, or | ('wc',... )\nfor line in command('ls'):  # iterable lines\ncommand.coroutine('ls')  # return coroutine\n\nfutured(command, 'ls')  # supports `map` interface\nasynced(command.coroutine, 'ls')  # supports `map` interface with timeout\n```\n\n### forked\n`forked` allows iteration in separate child processes.\n\n```python\nfrom futured import forked\n\nfor value in forked(values, max_workers=...):\n    # in a child process\n # in parent after children have exited\n```\n\n## Installation\n```console\n% pip install futured\n```\n\n## Tests\n100% branch coverage.\n\n```console\n% pytest [--cov]\n```\n",
    "bugtrack_url": null,
    "license": "Copyright 2022 Aric Coady  Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ",
    "summary": "Functional interface for concurrent futures, including async coroutines.",
    "version": "1.5",
    "project_urls": {
        "Changelog": "https://github.com/coady/futured/blob/main/CHANGELOG.md",
        "Documentation": "https://coady.github.io/futured",
        "Homepage": "https://github.com/coady/futured",
        "Issues": "https://github.com/coady/futured/issues"
    },
    "split_keywords": [
        "concurrent",
        " futures",
        " threads",
        " processes",
        " async",
        " asyncio"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "5c13402b0ce134617b7c2c5d5f27e74c921614fed0ce6bc90af285101f322b52",
                "md5": "dacfae0d3bf1122f84083ede34371e73",
                "sha256": "293310e9753bca51b772f24cc7a35c61c7834188384d37682f7ef03970a87555"
            },
            "downloads": -1,
            "filename": "futured-1.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "dacfae0d3bf1122f84083ede34371e73",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 6890,
            "upload_time": "2024-06-02T23:23:00",
            "upload_time_iso_8601": "2024-06-02T23:23:00.917092Z",
            "url": "https://files.pythonhosted.org/packages/5c/13/402b0ce134617b7c2c5d5f27e74c921614fed0ce6bc90af285101f322b52/futured-1.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ab4c3fb3df57b2670e433197c8706347c260cb2a1df5c22917a4e6d9559b4b88",
                "md5": "a2c1e15340ed70d098204a2b567a5bee",
                "sha256": "2967a5260973dccb75ad06b19fdf0fd38d9a7fe33ba9d85c09941f894c942510"
            },
            "downloads": -1,
            "filename": "futured-1.5.tar.gz",
            "has_sig": false,
            "md5_digest": "a2c1e15340ed70d098204a2b567a5bee",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 7684,
            "upload_time": "2024-06-02T23:23:02",
            "upload_time_iso_8601": "2024-06-02T23:23:02.658898Z",
            "url": "https://files.pythonhosted.org/packages/ab/4c/3fb3df57b2670e433197c8706347c260cb2a1df5c22917a4e6d9559b4b88/futured-1.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-02 23:23:02",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "coady",
    "github_project": "futured",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "futured"
}
        
Elapsed time: 3.78177s