Package: easync
EAsync – easy async decorator and promises@asyncDecorator around the functions for them to be asynchronous.Used as a simple decorator or along with named arguments. Preserves function’s or method’s docs, names and other stuff
usingfunctools.wraps.When the wrapped function is called, it produces thePromiseof itself.Usage:>>> from easync import async
>>> @async
>>> def f1():
>>>    # some heavy-weight code>>> @async(daemon=True, print_exception=False)
>>> def f2():
>>>     # some faulty daemon we don't really care about>>> @async(print_exception=logging.WARNING)
>>> def f3():
>>>     # setting another logging level>>> f1().wait()
<result>
>>> f2()  # started daemon
easync.Promise(...)
>>> f3().then(callback, error)  # notice, here the print_exception is suppressed (see Promise doc for more)
easync.Promise(...)param function:The function to be decorated.param Boolean daemon:Optional. Create the daemon thread, that will die when no other threads left.param print_exception:Log level to log the exception, if any, or None to mute it. Seelogging.param no_promise:Will not return a thing, instead of returningPromise, good for decorating, for example, Tornado
handlers.return:Wrapped function,Promisegenerator.PromiseThis is a threading wrapper that performs asynchronous call of the provided function.
The behaviour is inspired by JavaScript Promises, but differs in several points.First, the resolution is based upon the return of the function beneath.
On successful return, the result is stored inPromise.resultOn exception, exception is stored inPromise.exceptionMore about howPromiseresolves inResolving Promises.You can add callbacks by using methodsPromise.thenorPromise.catchThey will create a newPromiseresolving in either the resolution of the previous one or the underlying callback.If at the final stage no exception is processed or were generated new ones, they will be printed.Basic usage:>>> from easync import Promise
>>> promise = Promise(func)(...args)
>>> promise.wait()
<result>  # if any
>>> promise.result
<result>  # if any
>>> promise.exception
Exception  # if something went wrong
>>> promise.exc_info
Tuple (Exception.__class__, Exception, traceback)  # if anyCallbacks usage:>>> def callback(result):
>>>     do_stuff(result)
>>> def error(exception, exc_info):
>>>     my_log(exception, exc_info=exc_info)
>>> def some_final(_):
>>>     cleanup()
>>> Promise(func)(...args).then(callback, error).then(some_final)
Promise(...)Promise.CallableThe to-be-runned function.Promise.resultThis parameter holds the result the underlying function returned.Promise.exceptionThis parameter holds the exception if the underlying function fails.Promise.exc_infoThis parameter holds the exception information tuple if the underlying function fails and the tuple was recovered.
In case ofPromise.reject, it will be None.Promise.resolvedTrue if the function resolves. More about it inResolving Promises.Promise.startedthreading.Event, sets when thread is started.Promise.finishedthreading.Event, sets when thread is finished, no matter where had it been resolved or not.Promise.print_exceptionEnables exception printout if caught. Uses logging to do so and has to be one of logging levels.FalseorNonedisable. Also automatically sets to False when a dependentPromisecreated throughPromise.thenorPromise.catch.Resolving PromisesFunctionsIf thePromiseis constructed with a function, it will resolve in it’s return or reject with the caught exception.Other PromisesJust resolves in the same way the other one is resolved. Printouts will be suppressed in the first one.Events and ConditionsIfPromiseis based onthreading.Eventorthreading.Condition, it is resolved when the underlying Event or
Condition occurs. The type testing is duck-type for having thewaitmethod, so anything using the interface of
waiting can be resolved, for example other Promises, or threads.The resolving is based on testingis_failedon the object, and if that one returns, thePromiserejects. Otherwise,
theget_resultis called to obtain the result. Both are duck-type thingeys.Anything elseResolves successfully with the result equals to the passed-in argument.Promise.__init____init__(function[, daemon=False, print_exception=logging.ERROR])The constructor creates athreading.Threadwrapping thefunction.
To start it, call the resulting object as a function with it’s arguments. (Explained inPromise.__call__)>>> promise = Promise(func, print_exception=None)
>>> promise()param function:Function, Event, Condition, or anything else to resolve.param daemon:Sets up daemon flag in the thread. May be set later. Optional.param print_exception:Sets up the final exception printing level. PassFalseto suppress.Promise.__call____call__(*args,**kwargs)Starts the thread and passes the arguments of the function into it.
Returns self, for simple addingPromise.then,Promise.waitorPromise.catch.Promise.waitwait([timeout=None])Pauses the current thread to wait until the underlying promise resolves.Iftimeoutis set, raiseseasync.TimeoutErrorif it’s reached.Returns result of the underlying function if there’s any.Promise.thenthen([resolved=None,rejected=None, print_exception=Promise.print_exception])This method sets callbacks for aPromise.NOTEthis method suppresses thePromisedefault error handling by settingPromise.print_exceptiontoFalse.
You can then re-enable printouts manually, overriding thePromise.print_exceptionyourself.NOTEcalling this method twice on the samePromiseobject will result in duplicated exception printouts unless
changed.The result is a newPromisewhich resolves in:callback exception:If the called callback (eitherresolvedorrejected) failed or raised anything.reject:If the underlyingPromiserejected and norejectedcallback was passed.callback return:The result of the called callback.resolve:The result of the underlyingPromiseif it resolves and noresolvedcallback was passed.This is done to have this kind of behaviour:>>> Promise(action)(...args).then(parse_result).then(parse_one_more_result).catch(any_exception).then(cleanup)function resolved(result):The positive callback for thePromise. Has to accept one positional
argument - the result.function rejected(exception, exc_info):The negative callback for thePromise. Has to accept two positional
arguments - the caught exception and it’s exc_info.print_exception:Passed into the corresponding argument of the newly createdPromise.return:NewPromise.Promise.catchcatch([callback=None,print_exception=Promise.print_exception])The same asPromise.then(resolved=None, callback, print_exception).Promise static methodsPromise.resolvePromise.resolve(thing)Resolvesthing, regardless of what it is, to result.param thing:anyreturn:resolvedPromisewith thePromise.resultequals tothing.Promise.rejectPromise.reject(thing)Rejectsthing, regardless of what it is.NOTE, if this will be called, thePromise.exc_infowill be set None.param thing:anyreturn:rejectedPromisewith thePromise.exceptionequals tothing.Promise.allPromise.all(things)Resolves whenallthe items in theenumerate(things)are resolved.
Or rejects whenanyof the items is rejected.param things:listof things or anything to beenumerate’d.result:listof results of all the Promises for each of the items.exception:first caught exception.Promise.racePromise.race(things)Resolves whenanyof the items in theenumerate(things)is resolved.
Or rejects whenanyof the items is rejected.param things:listof things or anything to beenumerate’d.result:the result of the first resolved item.exception:first caught exception.Other functionsget_resultget_result(obj)Returns the first found attribute ofresultorsuccessof the object obj, if any. Otherwise returnsNone.is_failedis_failed(obj)Returns:found property:if one oferror,exception,failureis found.True:if one offailedoris_failedis true.True:ifsuccessis present and isFalse.None:Otherwise