Pyjo.Promise - Promises/A+¶
import Pyjo.UserAgent
from Pyjo.Promise import Promise
# Wrap continuation-passing style APIs with promises
ua = Pyjo.UserAgent.new()
def get_p(url):
promise = Promise()
def cb(ua, tx):
err = tx.error
if not err or err.get('code'):
promise.resolve(tx)
else:
promise.reject(err['message'])
ua.get(url, cb)
return promise
# Or import the module, as in Google Python Style Guide
import Pyjo.Promise
import Pyjo.UserAgent
# Wrap continuation-passing style APIs with promises
ua = Pyjo.UserAgent.new()
def get_p(url):
promise = Pyjo.Promise.new()
def cb(ua, tx):
err = tx.error
if not err or err.get('code'):
promise.resolve(tx)
else:
promise.reject(err['message'])
ua.get(url, cb)
return promise
# Perform non-blocking operations sequentially
def mojo_cb(mojo):
print(mojo.res.code)
return get_p('https://metacpan.org')
get_p('https://mojolicious.org').then(mojo_cb).then(
lambda cpan: print(cpan.res.code)
).catch(lambda err: warn(f'Something went wrong: {err}')).wait()
# Synchronize non-blocking operations (all)
mojo = get_p('https://mojolicious.org')
cpan = get_p('https://metacpan.org')
Pyjo.Promise.all(mojo, cpan).then(
lambda mojo, cpan: print(mojo[0].res.code, cpan[0].res.code)
).catch(lambda err: warn(f'Something went wrong: {err}')).wait()
# Synchronize non-blocking operations (race)
mojo = get_p('https://mojolicious.org')
cpan = get_p('https://metacpan.org')
Pyjo.Promise.race(mojo, cpan).then(
lambda tx: print(tx.req.url, 'won!')
).catch(lambda err: warn(f'Something went wrong: {err}')).wait()
# Await a promise in a coroutine
@Pyjo.Promise.coroutine
async def code(url):
tx = await get_p(url)
return tx.res.code
code('https://mojolicious.org').then(print).wait()
Pyjo.Promise is a Python implementation of
Promises/A+ and a superset of
ES6 Promises.
States¶
A promise is an object representing the eventual completion or failure of a non-blocking operation. It allows non-blocking functions to return values, like blocking functions. But instead of immediately returning the final value, the non-blocking function returns a promise to supply the value at some point in the future.
A promise can be in one of three states:
- pending
Initial state, neither fulfilled nor rejected.
- fulfilled
Meaning that the operation completed successfully.
- rejected
Meaning that the operation failed.
A pending promise can either be fulfilled with a value or rejected with a
reason. When either happens, the associated handlers queued up by a promise’s
then() method are called.
Values¶
A promise is fulfilled or rejected with any number of values, and the
handlers get them as arguments. What a handler returns is the value of the new
promise, None is no value, and a promise is adopted, so a handler that
passes several values on returns a promise of them.
promise.then(lambda *values: Pyjo.Promise.resolve(*values))
Coroutines¶
await promise waits for the promise in a coroutine, and gives its value,
a tuple of several values, or None for none. A rejection raises the
exception the promise was rejected with, or a Pyjo.Exception of the
first reason. A coroutine is a promise with new() or
coroutine(). The reactor of the event loop runs it: a coroutine awaits the
promises of Pyjoyment with any reactor, and with Pyjo.Reactor.Asyncio
anything of asyncio too, and a promise can be awaited in any asyncio task.
Another awaitable, as a future of asyncio, is a promise with
new() too, and to_future() turns a
promise into a future of the reactor.
async def main():
title = (await get_p('https://mojolicious.org')).res.dom().at('title').text
Debugging¶
You can set the PYJO_PROMISE_DEBUG environment variable to get some
advanced diagnostics information printed to sys.stderr.
PYJO_PROMISE_DEBUG=1
See also¶
Pyjoyment, https://mojolicious.org.
Ported from Mojo::Promise of Mojolicious 9.52.
Functions¶
- class Pyjo.Promise.Pyjo_Promise(cb: Callable[[Handler, Handler], Anything] | Awaitable[Any] | Future[Any] | None = None)[source]¶
Pyjo.Promiseinherits all methods fromPyjo.Baseand implements the following new ones.- __await__() Generator[Any, Any, Any][source]¶
value = await promise
Wait for the promise in a coroutine and return its value, a tuple of several values, or
Nonefor none, or raise the exception it was rejected with, or aPyjo.Exceptionof the first reason.
- classmethod all(*promises: Pyjo_Promise) Pyjo_Promise[source]¶
new = Pyjo.Promise.all(*promises)
Returns a new
Pyjo.Promiseobject that either fulfills when all of the passedPyjo.Promiseobjects have fulfilled or rejects as soon as one of them rejects. If the returned promise fulfills, it is fulfilled with the values from the fulfilled promises in the same order as the passed promises, a list of the values of each.
- classmethod all_settled(*promises: Pyjo_Promise) Pyjo_Promise[source]¶
new = Pyjo.Promise.all_settled(*promises)
Returns a new
Pyjo.Promiseobject that fulfills when all of the passedPyjo.Promiseobjects have fulfilled or rejected, with dicts that describe the outcome of each promise.
- classmethod any(*promises: Pyjo_Promise) Pyjo_Promise[source]¶
new = Pyjo.Promise.any(*promises)
Returns a new
Pyjo.Promiseobject that fulfills as soon as one of the passedPyjo.Promiseobjects fulfills, with the value from that promise.
- catch(cb: Handler) Pyjo_Promise[source]¶
new = promise.catch(lambda *reason: ...)
Appends a rejection handler callback to the promise, and returns a new
Pyjo.Promiseobject resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled.# Longer version new = promise.then(None, lambda *reason: ...) # Pass along the rejection reason def cb(*reason): warn(f'Something went wrong: {reason[0]}') return Pyjo.Promise.reject(*reason) promise.catch(cb) # Change the rejection reason promise.catch(lambda *reason: f'This is bad: {reason[0]}')
- clone() Pyjo_Promise[source]¶
new = promise.clone()
Return a new
Pyjo.Promiseobject cloned from this promise that is still pending.
- property ioloop: Pyjo_IOLoop[source]¶
loop = promise.ioloop promise.ioloop = Pyjo.IOLoop.new()
Event loop object to control, defaults to the global
Pyjo.IOLoopsingleton. Note that this attribute is weakened.
- lastly(cb: Callable[[], Any]) Pyjo_Promise[source]¶
new = promise.lastly(lambda: ...)
Appends a fulfillment and rejection handler to the promise, and returns a new
Pyjo.Promiseobject resolving to the original fulfillment value or rejection reason.finally_is an alias, the name of Mojolicious with an underscore.# Do something on fulfillment and rejection promise.lastly(lambda: print('We are done!'))
- classmethod map(cb: Callable[[Any], Pyjo_Promise], *items: Any, concurrency: int = 0) Pyjo_Promise[source]¶
new = Pyjo.Promise.map(lambda item: ..., *items) new = Pyjo.Promise.map(lambda item: ..., *items, concurrency=3)
Apply a function that returns a
Pyjo.Promiseto each item in a list of items while optionally limiting concurrency. Returns aPyjo.Promisethat collects the results in the same manner asall(). If any item’s promise is rejected, any remaining items which have not yet been mapped will not be.# Perform 3 requests at a time concurrently Pyjo.Promise.map(lambda url: ua.get_p(url), *urls, concurrency=3).then( lambda *results: [print(r[0].res.dom().at('title').text) for r in results] )
These options are currently available:
- concurrency
concurrency=3
The maximum number of items that are in progress at the same time.
- classmethod race(*promises: Pyjo_Promise) Pyjo_Promise[source]¶
new = Pyjo.Promise.race(*promises)
Returns a new
Pyjo.Promiseobject that fulfills or rejects as soon as one of the passedPyjo.Promiseobjects fulfills or rejects, with the value or reason from that promise.
- reject(**kwargs: P) R[source]¶
new = Pyjo.Promise.reject(*reason) promise = promise.reject(*reason)
Build rejected
Pyjo.Promiseobject or reject the promise with one or more rejection reasons.# Longer version promise = Pyjo.Promise.new().reject(*reason)
- resolve(**kwargs: P) R[source]¶
new = Pyjo.Promise.resolve(*value) promise = promise.resolve(*value)
Build resolved
Pyjo.Promiseobject or resolve the promise with one or more fulfillment values.# Longer version promise = Pyjo.Promise.new().resolve(*value)
- then(resolve: Handler | None = None, reject: Handler | None = None) Pyjo_Promise[source]¶
new = promise.then(lambda *value: ...) new = promise.then(lambda *value: ..., lambda *reason: ...) new = promise.then(None, lambda *reason: ...)
Appends fulfillment and rejection handlers to the promise, and returns a new
Pyjo.Promiseobject resolving to the return value of the called handler.# Pass along the fulfillment value or rejection reason def value_cb(*value): print(f'The result is {value[0]}') return Pyjo.Promise.resolve(*value) def reason_cb(*reason): warn(f'Something went wrong: {reason[0]}') return Pyjo.Promise.reject(*reason) promise.then(value_cb, reason_cb) # Change the fulfillment value or rejection reason promise.then(lambda *value: f'This is good: {value[0]}', lambda *reason: f'This is bad: {reason[0]}')
- timeout(**kwargs: P) R[source]¶
new = Pyjo.Promise.timeout(5, 'Timeout!') promise = promise.timeout(5, 'Timeout!') promise = promise.timeout(5)
Create a new
Pyjo.Promiseobject with a timeout or attach a timeout to an existing promise. The promise will be rejected after the given amount of time in seconds with a reason, which defaults toPromise timeout, unless it has already been settled.
- timer(**kwargs: P) R[source]¶
new = Pyjo.Promise.timer(5, 'Success!') promise = promise.timer(5, 'Success!') promise = promise.timer(5)
Create a new
Pyjo.Promiseobject with a timer or attach a timer to an existing promise. The promise will be resolved after the given amount of time in seconds with or without a value, unless it has already been settled. Note that this does not delay the resolution of an existing promise, to add a delay to a promise chain you have to return a new timer promise instead.# Wait 5 seconds between two steps promise.then(lambda *_: Pyjo.Promise.timer(5)).then(lambda *_: print('Five seconds later'))
- to_future() Future[Any][source]¶
future = promise.to_future()
Turn promise into a future of the reactor of
ioloop, anasyncio.Futureof its loop withPyjo.Reactor.Asyncio, or aconcurrent.futures.Futurewith a reactor without asyncio, asPyjo.Reactor.Poll. The future is done when the promise is fulfilled or rejected, with whatawait promisegives: its value, a tuple of several values, orNonefor none, or the exception it was rejected with, or aPyjo.Exceptionof the first reason.# Print the value when the future is done future = Pyjo.Promise.timer(1, 'Done!').to_future() future.add_done_callback(lambda future: print(future.result()))
- Pyjo.Promise.all(*promises: Pyjo_Promise) Pyjo_Promise[source]¶
new = Pyjo.Promise.all(*promises)
Returns a new
Pyjo.Promiseobject that either fulfills when all of the passedPyjo.Promiseobjects have fulfilled or rejects as soon as one of them rejects. If the returned promise fulfills, it is fulfilled with the values from the fulfilled promises in the same order as the passed promises, a list of the values of each.
- Pyjo.Promise.all_settled(*promises: Pyjo_Promise) Pyjo_Promise[source]¶
new = Pyjo.Promise.all_settled(*promises)
Returns a new
Pyjo.Promiseobject that fulfills when all of the passedPyjo.Promiseobjects have fulfilled or rejected, with dicts that describe the outcome of each promise.
- Pyjo.Promise.any(*promises: Pyjo_Promise) Pyjo_Promise[source]¶
new = Pyjo.Promise.any(*promises)
Returns a new
Pyjo.Promiseobject that fulfills as soon as one of the passedPyjo.Promiseobjects fulfills, with the value from that promise.
- Pyjo.Promise.coroutine(func: Callable[[P], Coroutine[Any, Any, Any]]) Callable[[P], Pyjo_Promise][source]¶
@Pyjo.Promise.coroutine async def title(url): tx = await ua.get_p(url) return tx.res.dom().at('title').text title('https://mojolicious.org').then(print).wait()
Turn a coroutine function into a function that returns a
Pyjo.Promiseof the coroutine, asasync subdoes in Mojo.
- Pyjo.Promise.map(cb: Callable[[Any], Pyjo_Promise], *items: Any, concurrency: int = 0) Pyjo_Promise[source]¶
new = Pyjo.Promise.map(lambda item: ..., *items) new = Pyjo.Promise.map(lambda item: ..., *items, concurrency=3)
Apply a function that returns a
Pyjo.Promiseto each item in a list of items while optionally limiting concurrency. Returns aPyjo.Promisethat collects the results in the same manner asall(). If any item’s promise is rejected, any remaining items which have not yet been mapped will not be.# Perform 3 requests at a time concurrently Pyjo.Promise.map(lambda url: ua.get_p(url), *urls, concurrency=3).then( lambda *results: [print(r[0].res.dom().at('title').text) for r in results] )
These options are currently available:
- concurrency
concurrency=3
The maximum number of items that are in progress at the same time.
- Pyjo.Promise.race(*promises: Pyjo_Promise) Pyjo_Promise[source]¶
new = Pyjo.Promise.race(*promises)
Returns a new
Pyjo.Promiseobject that fulfills or rejects as soon as one of the passedPyjo.Promiseobjects fulfills or rejects, with the value or reason from that promise.
- Pyjo.Promise.reject(*args: P, **kwargs: P) R[source]¶
new = Pyjo.Promise.reject(*reason) promise = promise.reject(*reason)
Build rejected
Pyjo.Promiseobject or reject the promise with one or more rejection reasons.# Longer version promise = Pyjo.Promise.new().reject(*reason)
- Pyjo.Promise.resolve(*args: P, **kwargs: P) R[source]¶
new = Pyjo.Promise.resolve(*value) promise = promise.resolve(*value)
Build resolved
Pyjo.Promiseobject or resolve the promise with one or more fulfillment values.# Longer version promise = Pyjo.Promise.new().resolve(*value)
- Pyjo.Promise.timeout(*args: P, **kwargs: P) R[source]¶
new = Pyjo.Promise.timeout(5, 'Timeout!') promise = promise.timeout(5, 'Timeout!') promise = promise.timeout(5)
Create a new
Pyjo.Promiseobject with a timeout or attach a timeout to an existing promise. The promise will be rejected after the given amount of time in seconds with a reason, which defaults toPromise timeout, unless it has already been settled.
- Pyjo.Promise.timer(*args: P, **kwargs: P) R[source]¶
new = Pyjo.Promise.timer(5, 'Success!') promise = promise.timer(5, 'Success!') promise = promise.timer(5)
Create a new
Pyjo.Promiseobject with a timer or attach a timer to an existing promise. The promise will be resolved after the given amount of time in seconds with or without a value, unless it has already been settled. Note that this does not delay the resolution of an existing promise, to add a delay to a promise chain you have to return a new timer promise instead.# Wait 5 seconds between two steps promise.then(lambda *_: Pyjo.Promise.timer(5)).then(lambda *_: print('Five seconds later'))