JavaScript-style async programming for Python.

Overview

promisio

Build status codecov

JavaScript-style async programming for Python.

Examples

Create a promise-based async function using the promisify decorator. It works on both sync and async functions!

from promisio import promisify

@promisify
async def f():
    await asyncio.sleep(1)
    return 42

@promisify
def g(x):
    return x * 2

async def main():
    print(await f())  # prints 42
    print(await g(42))  # prints 84

    promise = f()  # runs function in the background without waiting
    # ... do other stuff here in parallel with f running
    await promise  # finally wait for f to complete

The return value of the decorated function is a JavaScript-style promise object that can be awaited. The then(), catch() and finally_() methods to chain promises work as in JavaScript. The Promise.all(), Promise.all_settled(), Promise.any(), Promise.race(), Promise.resolve() and Promise.reject() are also available. Promises in this package are extended to also support cancellation via the cancel() and cancelled() methods.

Resources

You might also like...
A functional standard library for Python.

Toolz A set of utility functions for iterators, functions, and dictionaries. See the PyToolz documentation at https://toolz.readthedocs.io LICENSE New

Python Classes Without Boilerplate

attrs is the Python package that will bring back the joy of writing classes by relieving you from the drudgery of implementing object protocols (aka d

🔩 Like builtins, but boltons. 250+ constructs, recipes, and snippets which extend (and rely on nothing but) the Python standard library. Nothing like Michael Bolton.

Boltons boltons should be builtins. Boltons is a set of over 230 BSD-licensed, pure-Python utilities in the same spirit as — and yet conspicuously mis

Retrying library for Python

Tenacity Tenacity is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just

Simple yet flexible natural sorting in Python.

natsort Simple yet flexible natural sorting in Python. Source Code: https://github.com/SethMMorton/natsort Downloads: https://pypi.org/project/natsort

A Python utility belt containing simple tools, a stdlib like feel, and extra batteries. Hashing, Caching, Timing, Progress, and more made easy!
A Python utility belt containing simple tools, a stdlib like feel, and extra batteries. Hashing, Caching, Timing, Progress, and more made easy!

Ubelt is a small library of robust, tested, documented, and simple functions that extend the Python standard library. It has a flat API that all behav

Retrying is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just about anything.

Retrying Retrying is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just

Pampy: The Pattern Matching for Python you always dreamed of.
Pampy: The Pattern Matching for Python you always dreamed of.

Pampy: Pattern Matching for Python Pampy is pretty small (150 lines), reasonably fast, and often makes your code more readable and hence easier to rea

Hot reloading for Python
Hot reloading for Python

Hot reloading for Python

Comments
  • [Question] How to reject a Promise?

    [Question] How to reject a Promise?

    Discussed in https://github.com/miguelgrinberg/promisio/discussions/2

    Originally posted by ishan1608 April 16, 2022 Hey Miguel Grinberg,

    How do I reject a promise? I have this scenario where I have to make two HTTP calls and one call to AWS Cognito. Calling them serially is working at the moment. But I want to call them in parallel as they are not dependent on each other. I couldn't figure out how to reject from a function which is decorated with @promisify

    So, I tried using the Promise class itself. I am going to provide my attempt and the error that I am getting. Any help would be appreciated.

    Code:

    import asyncio
    from asyncio.exceptions import CancelledError, InvalidStateError
    from datetime import datetime
    
    from promisio import promisify, Promise
    
    
    def task_a(arg1, arg2):
        def _task_a(resolve, reject):
            val = f'task a {arg1} : {arg2} -- {datetime.now()}'
            print(val)
            some_condition = 5
            if some_condition == 5:
                return reject(BaseException('Failing task a'))
            return resolve(val)
    
        return Promise(f=_task_a)
    
    
    @promisify
    async def task_b(arg1, arg2):
        await asyncio.sleep(2.5)
        val = f'task b {arg1} : {arg2} -- {datetime.now()}'
        print(val)
        return val
    
    
    @promisify
    async def task_c(arg1, arg2):
        await asyncio.sleep(3)
        val = f'task c {arg1} : {arg2} -- {datetime.now()}'
        print(val)
        return val
    
    
    async def main():
        pr_b = task_b(2, 2)
        print(pr_b)
    
        try:
            pr_a = task_a(1, 1)
            print(pr_a)
        except InvalidStateError as error:
            print('task_a threw error')
            print(error)
        except CancelledError as error:
            print('task_a threw error')
            print(error)
        except BaseException as error:
            print('task_a threw error')
            print(error)
    
        pr_c = task_c(3, 3)
        print(pr_c)
        # await pr_a
        # await pr_b
        # await pr_c
        pr_all = Promise.all([pr_a, pr_b, pr_c])
        pr_all = pr_all.then(on_resolved=lambda x: print(f'All resolved {x}'), on_rejected=lambda x: print(f'Rejected {x}'))
        await pr_all
    
    
    if __name__ == '__main__':
        asyncio.run(main())
    
    

    Error:

    <promisio.TaskPromise object at 0x7fb8519f0250>
    task a 1 : 1 -- 2022-04-16 09:55:45.791987
    <promisio.Promise object at 0x7fb8519f02e0>
    <promisio.TaskPromise object at 0x7fb8519f0340>
    Rejected Failing task a
    Future exception was never retrieved
    future: <Future finished exception=InvalidStateError('invalid state')>
    Traceback (most recent call last):
      File "/home/ishan/.venv/heka/lib/python3.8/site-packages/promisio/__init__.py", line 272, in _handle_done
        result = future.result()
      File "/home/ishan/.venv/heka/lib/python3.8/site-packages/promisio/__init__.py", line 272, in _handle_done
        result = future.result()
      File "/home/ishan/.venv/heka/lib/python3.8/site-packages/promisio/__init__.py", line 272, in _handle_done
        result = future.result()
    asyncio.exceptions.CancelledError
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/home/ishan/.venv/heka/lib/python3.8/site-packages/promisio/__init__.py", line 256, in _handle_callback
        callback_result = callback(result)
      File "/home/ishan/.venv/heka/lib/python3.8/site-packages/promisio/__init__.py", line 250, in _reject
        self.future.set_exception(error)
    asyncio.exceptions.InvalidStateError: invalid state
    Future exception was never retrieved
    future: <Future finished exception=InvalidStateError('invalid state')>
    Traceback (most recent call last):
      File "/home/ishan/.venv/heka/lib/python3.8/site-packages/promisio/__init__.py", line 272, in _handle_done
        result = future.result()
      File "/home/ishan/.venv/heka/lib/python3.8/site-packages/promisio/__init__.py", line 272, in _handle_done
        result = future.result()
      File "/home/ishan/.venv/heka/lib/python3.8/site-packages/promisio/__init__.py", line 272, in _handle_done
        result = future.result()
    asyncio.exceptions.CancelledError
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/home/ishan/.venv/heka/lib/python3.8/site-packages/promisio/__init__.py", line 256, in _handle_callback
        callback_result = callback(result)
      File "/home/ishan/.venv/heka/lib/python3.8/site-packages/promisio/__init__.py", line 250, in _reject
        self.future.set_exception(error)
    asyncio.exceptions.InvalidStateError: invalid state
    
    ```</div>
    opened by ishan1608 1
  • Running promisio in Google Colab

    Running promisio in Google Colab

    Hi there,

    I've been trying to figure a clean solution to use async task in python and I very much like how this library can promisify both async or un-async function. So I gave it a try.

    As a simple use case, I've been using pyppeteer which use a lot of async call in their API. The idea is just to make screenshot from google and bing. I want to chain call from main and main2 and thought about using Promise.all

    In my testing attempt I've also been using the library nest_asyncio, but my end goal would be to avoid using this library as much as possible.

    Anyway, see the following code I shared on google colab: https://colab.research.google.com/drive/16aXwZZX6nSMtGe4_wfMcP8pcA6gzav1-

    So, my issue is that I've been experiencing trouble when running several cell at once. Google colab tend to hang or cause weird issue on the order on which screenshot should be overwritten. So I've been wondering if there's a way to chain these cell operation in a smooth manner. Note: I'm also returning value from main to main2

    I thought about using asyncio.run(main().then(main2)) but there's issue with unpacking the returned tuple. So my initial feedback has been about whether this intended? It's been a long time since I've been using the JavaScript async model, so this alright.

    I believe there might be some other issue going on as google colab is an environment which is always involving, but I would appreciate any help about how to deal with these issues.

    question 
    opened by antogerva 1
Owner
Miguel Grinberg
Miguel Grinberg
✨ Voici un code en Python par moi, et en français qui permet d'exécuter du Javascript en Python.

JavaScript In Python ❗ Voici un code en Python par moi, et en français qui permet d'exécuter du Javascript en Python. ?? Une vidéo pour vous expliquer

MrGabin 4 Mar 28, 2022
Small project to interact with python, C, HTML, JavaScript, PHP.

Micro Hidroponic Small project to interact with python, C, HTML, JavaScript, PHP. Table of Contents General Info Technologies Used Screenshots Usage P

Filipe Martins 1 Nov 10, 2021
async parser for JET

This project is mainly aims to provide an async parsing option for NTDS.dit database file for obtaining user secrets.

null 15 Mar 8, 2022
Creating low-level foundations and abstractions for asynchronous programming in Python.

DIY Async I/O Creating low-level foundations and abstractions for asynchronous programming in Python (i.e., implementing concurrency without using thr

Doc Jones 4 Dec 11, 2021
Allows you to canibalize methods from classes effectively implementing trait-oriented programming

About This package enables code reuse in non-inheritance way from existing classes, effectively implementing traits-oriented programming pattern. Stor

null 1 Dec 13, 2021
Simple python module to get the information regarding battery in python.

Battery Stats A python3 module created for easily reading the current parameters of Battery in realtime. It reads battery stats from /sys/class/power_

Shreyas Ashtamkar 5 Oct 21, 2022
ticktock is a minimalist library to view Python time performance of Python code.

ticktock is a minimalist library to view Python time performance of Python code.

Victor Benichoux 30 Sep 28, 2022
Python @deprecat decorator to deprecate old python classes, functions or methods.

deprecat Decorator Python @deprecat decorator to deprecate old python classes, functions or methods. Installation pip install deprecat Usage To use th

null 12 Dec 12, 2022
A python package containing all the basic functions and classes for python. From simple addition to advanced file encryption.

A python package containing all the basic functions and classes for python. From simple addition to advanced file encryption.

PyBash 11 May 22, 2022
Find dependent python scripts of a python script in a project directory.

Find dependent python scripts of a python script in a project directory.

null 2 Dec 5, 2021