comparison sat/tools/utils.py @ 3215:bfa1bde97f48

core (tools/utils): new `asDeferred` function: asDeferred is similar to defer.maybeCoroutine, and also handles coroutine.
author Goffi <goffi@goffi.org>
date Fri, 13 Mar 2020 17:46:27 +0100
parents 559a625a236b
children 4396bf14f5fc
comparison
equal deleted inserted replaced
3214:8d92d4d829fb 3215:bfa1bde97f48
27 import sys 27 import sys
28 import random 28 import random
29 import inspect 29 import inspect
30 import textwrap 30 import textwrap
31 import functools 31 import functools
32 from twisted.python import procutils 32 from asyncio import iscoroutine
33 from twisted.python import procutils, failure
34 from twisted.internet import defer
33 from sat.core.constants import Const as C 35 from sat.core.constants import Const as C
34 from sat.core.log import getLogger 36 from sat.core.log import getLogger
35 37
36 log = getLogger(__name__) 38 log = getLogger(__name__)
37 39
86 ), 88 ),
87 locals(), 89 locals(),
88 ) 90 )
89 91
90 return method 92 return method
93
94
95 def asDeferred(func, *args, **kwargs):
96 """Call a method and return a Deferred
97
98 the method can be a simple callable, a Deferred or a coroutine.
99 It is similar to defer.maybeDeferred, but also handles coroutines
100 """
101 try:
102 ret = func(*args, **kwargs)
103 except Exception as e:
104 return defer.fail(failure.Failure(e))
105 else:
106 if iscoroutine(ret):
107 return defer.ensureDeferred(ret)
108 elif isinstance(ret, defer.Deferred):
109 return ret
110 elif isinstance(ret, failure.Failure):
111 return defer.fail(ret)
112 else:
113 return ret
91 114
92 115
93 def xmpp_date(timestamp=None, with_time=True): 116 def xmpp_date(timestamp=None, with_time=True):
94 """Return date according to XEP-0082 specification 117 """Return date according to XEP-0082 specification
95 118