コード例 #1
0
ファイル: app0.py プロジェクト: arheo/python_core
def main():
    print('-' * 80)
    print(str.format(
        '[*] coroutine is coroutine function => {}',
        inspect.iscoroutinefunction(coroutine)
    ))
    print(str.format(
        '[*] subcoroutine is coroutine function => {}',
        inspect.iscoroutinefunction(subcoroutine)
    ))
    sub1 = subcoroutine('Subroutine')
    print(str.format(
        '[*] sub1 is coroutine object => {}', inspect.iscoroutine(sub1)
    ))
    coro1 = coroutine('Coroutine')
    print(str.format(
        '[*] coro1 is coroutine object => {}', inspect.iscoroutine(coro1)
    ))

    print('-' * 80)
    print(str.format(
        '[*] CoroutineClass is sub-class of Awaitable class => {}',
        issubclass(CoroutineClass, Awaitable)
    ))
    c1 = CoroutineClass('Coroutine #1', ['A', 'B', 'C'])
    print(str.format(
        '[*] c1 is awaitable object => {}', inspect.isawaitable(c1)
    ))
    print(str.format(
        '[*] c1 is instance of Awaitable class => {}',
        isinstance(c1, Awaitable)
    ))

    print('-' * 80)
コード例 #2
0
ファイル: decorators.py プロジェクト: TC01/cocotb
    def __init__(self, inst, parent):
        if hasattr(inst, "__name__"):
            self.__name__ = "%s" % inst.__name__
            self.log = SimLog("cocotb.coroutine.%s" % self.__name__, id(self))
        else:
            self.log = SimLog("cocotb.coroutine.fail")

        if sys.version_info[:2] >= (3, 5) and inspect.iscoroutine(inst):
            self._natively_awaitable = True
            self._coro = inst.__await__()
        else:
            self._natively_awaitable = False
            self._coro = inst
        self._started = False
        self._callbacks = []
        self._parent = parent
        self.__doc__ = parent._func.__doc__
        self.module = parent._func.__module__
        self.funcname = parent._func.__name__
        self._outcome = None

        if not hasattr(self._coro, "send"):
            self.log.error("%s isn't a valid coroutine! Did you use the yield "
                           "keyword?" % self.funcname)
            raise CoroutineComplete()
コード例 #3
0
ファイル: cache_task.py プロジェクト: sjdv1982/seamless
 def schedule_task(self, key, func, count, *, resultfunc=None, cancelfunc=None):
     assert count != 0
     if count > 0:
         if key not in self.tasks:
             future = asyncio.ensure_future(func)
             def cancelfunc2(f):
                 task = self.tasks.pop(key)
                 if future.cancelled():                                         
                     if cancelfunc is not None:
                         cancelfunc()
                 elif task.future.done():
                     exc = task.future.exception()
                     if exc is not None:
                         raise exc
                 else:
                     task.cancel()
                     if cancelfunc is not None:
                         cancelfunc()
             task = CacheTask(key, future, count, resultfunc, cancelfunc2)
             self.tasks[key] = task
         else:
             task = self.tasks[key]
             if inspect.iscoroutine(func):
                 asyncio.Task(func).cancel()
             task.incref(count)            
     else:
         task = self.tasks.get(key)
         if task is not None:
             task.decref(count)            
     return task
コード例 #4
0
ファイル: __init__.py プロジェクト: srossross/uvio
    def inner(*args, **kwargs):
        loop = Loop.create(func.__name__)

        coro = func(*args, **kwargs)

        if not iscoroutine(coro):
            raise Exception("{} is not a coroutine (returned from {})".format(coro, func))

        loop.next_tick(coro)

        if timeout:
            def stop_loop():
                loop.stop()
                raise Exception("timeout")


            timer = loop.set_timeout(stop_loop, timeout)
            # Don't wait for the timout to exit the loop
            timer.unref()

        loop.run()
        loop.close()

        if timeout:
            timer.close()

        if coro.cr_await is not None:
            coro.throw(Exception('coroutine {} should not be running at the end of the loop'.format(coro)))

        # This should not happend
        assert not loop._awaiting, loop._awaiting
        assert not loop.ready, loop.ready
コード例 #5
0
ファイル: coroutines.py プロジェクト: whqkdhfh13/sswp
 def __init__(self, gen, func=None):
     assert inspect.isgenerator(gen) or inspect.iscoroutine(gen), gen
     self.gen = gen
     self.func = func  # Used to unwrap @coroutine decorator
     self._source_traceback = traceback.extract_stack(sys._getframe(1))
     self.__name__ = getattr(gen, '__name__', None)
     self.__qualname__ = getattr(gen, '__qualname__', None)
コード例 #6
0
ファイル: event.py プロジェクト: awesome-python/asphalt
        async def do_dispatch():
            futures, exceptions = [], []
            for callback in listeners:
                try:
                    retval = callback(event)
                except Exception as e:
                    exceptions.append((callback, e))
                    if not return_future:
                        logger.exception('uncaught exception in event listener')
                else:
                    if isawaitable(retval):
                        if iscoroutine(retval):
                            retval = loop.create_task(retval)

                        futures.append((callback, retval))

            # For any callbacks that returned awaitables, wait for their completion and collect any
            # exceptions they raise
            for callback, awaitable in futures:
                try:
                    await awaitable
                except Exception as e:
                    exceptions.append((callback, e))
                    if not return_future:
                        logger.exception('uncaught exception in event listener')

            if exceptions and return_future:
                raise EventDispatchError(event, exceptions)
コード例 #7
0
ファイル: thread.py プロジェクト: drewja/curio
def spawn_thread(func=None, *args, daemon=False):
    '''
    Launch an async thread.  This mimicks the way a task is normally spawned. For
    example:

         t = await spawn_thread(func, arg1, arg2)
         ...
         await t.join()

    It can also be used as a context manager to launch a code block into a thread:

         async with spawn_thread():
             sync_op ...
             sync_op ...
    '''
    if func is None:
        return _AsyncContextManager()
    else:
        if iscoroutine(func) or meta.iscoroutinefunction(func):
            raise TypeError("spawn_thread() can't be used on coroutines")
        async def runner(args, daemon):
            t = AsyncThread(func, args=args, daemon=daemon)
            await t.start()
            return t
        return runner(args, daemon)
コード例 #8
0
ファイル: thread.py プロジェクト: drewja/curio
def AWAIT(coro, *args, **kwargs):
    '''
    Await for a coroutine in an asynchronous thread.  If coro is
    not a proper coroutine, this function acts a no-op, returning coro.
    '''
    # If the coro is a callable and it's identifiable as a coroutine function,
    # wrap it inside a coroutine and pass that.
    if callable(coro):
        if meta.iscoroutinefunction(coro) and hasattr(_locals, 'thread'):
            async def _coro(coro):
                return await coro(*args, **kwargs)
            coro = _coro(coro)
        else:
            coro = coro(*args, **kwargs)


    if iscoroutine(coro) or isgenerator(coro):
        if hasattr(_locals, 'thread'):
            return _locals.thread.AWAIT(coro)
        else:
            # Thought: Do we try to promote the calling thread into an "async" thread automatically?
            # Would require a running kernel. Would require a task dedicated to spawning the coro
            # runner.   Would require shutdown.  Maybe a context manager?
            raise errors.AsyncOnlyError('Must be used as async')
    else:
        return coro
コード例 #9
0
ファイル: _app.py プロジェクト: notoriousno/klein
def _call(instance, f, *args, **kwargs):
    if instance is not None or getattr(f, "__klein_bound__", False):
        args = (instance,) + args
    result = f(*args, **kwargs)
    if iscoroutine(result):
        result = ensureDeferred(result)
    return result
コード例 #10
0
ファイル: testing.py プロジェクト: leeclemens/tornado
 def pre_coroutine(self, *args, **kwargs):
     result = f(self, *args, **kwargs)
     if isinstance(result, Generator) or inspect.iscoroutine(result):
         self._test_generator = result
     else:
         self._test_generator = None
     return result
コード例 #11
0
ファイル: testing.py プロジェクト: leeclemens/tornado
 def __call__(self, *args, **kwargs):
     result = self.orig_method(*args, **kwargs)
     if isinstance(result, Generator) or inspect.iscoroutine(result):
         raise TypeError("Generator and coroutine test methods should be"
                         " decorated with tornado.testing.gen_test")
     elif result is not None:
         raise ValueError("Return value from test method ignored: %r" %
                          result)
コード例 #12
0
ファイル: async_neo.py プロジェクト: hivesolutions/netius
def ensure_generator(value):
    if legacy.is_generator(value):
        return True, value

    if hasattr(inspect, "iscoroutine") and\
        inspect.iscoroutine(value): #@UndefinedVariable
        return True, CoroutineWrapper(value)

    return False, value
コード例 #13
0
ファイル: discordbot.py プロジェクト: Azimath/discordbot
async def callEvents(eventName, commandObjects, *args, **kwargs):
    calledCount = 0
    for method,commandObject in COCallablesIterator(commandObjects, eventName):
        if not inspect.iscoroutine(method) and not inspect.iscoroutinefunction(method):
            method(*args, **kwargs)
        else:
            await method(*args, **kwargs)
        calledCount += 1
    return calledCount
コード例 #14
0
ファイル: testing.py プロジェクト: rgbkrk/tornado
 def pre_coroutine(self, *args, **kwargs):
     # type: (AsyncTestCase, *Any, **Any) -> Union[Generator, Coroutine]
     # Type comments used to avoid pypy3 bug.
     result = f(self, *args, **kwargs)
     if isinstance(result, Generator) or inspect.iscoroutine(result):
         self._test_generator = result
     else:
         self._test_generator = None
     return result
コード例 #15
0
ファイル: async_neo.py プロジェクト: hivesolutions/netius
def is_coroutine_object(generator):
    if legacy.is_generator(generator):
        return True

    if hasattr(inspect, "iscoroutine") and\
        inspect.iscoroutine(generator): #@UndefinedVariable
        return True

    return False
コード例 #16
0
ファイル: context.py プロジェクト: awesome-python/asphalt
    def get_value(self, ctx: 'Context'):
        assert check_argument_types()
        if self.value is None and self.creator is not None:
            self.value = self.creator(ctx)
            if iscoroutine(self.value):
                self.value = ensure_future(self.value)
            if self.context_attr:
                setattr(ctx, self.context_attr, self.value)

        return self.value
コード例 #17
0
ファイル: app3.py プロジェクト: arheo/python_core
    def __init__(self, *args):
        self._coros = deque()

        for coro in args:
            if inspect.iscoroutine(coro):
                self._coros.appendleft(coro)
            else:
                raise TypeError(str.format(
                    '[#] {} must be awaitable object provide {}',
                    coro, type(coro)
                ))
コード例 #18
0
ファイル: pc_rpc.py プロジェクト: amhankin/artiq
 async def _process_action(self, target, obj):
     if self._noparallel is not None:
         await self._noparallel.acquire()
     try:
         if obj["action"] == "get_rpc_method_list":
             members = inspect.getmembers(target, inspect.ismethod)
             doc = {
                 "docstring": inspect.getdoc(target),
                 "methods": {}
             }
             for name, method in members:
                 if name.startswith("_"):
                     continue
                 method = getattr(target, name)
                 argspec = inspect.getfullargspec(method)
                 doc["methods"][name] = (dict(argspec._asdict()),
                                         inspect.getdoc(method))
             if self.builtin_terminate:
                 doc["methods"]["terminate"] = (
                     {
                         "args": ["self"],
                         "defaults": None,
                         "varargs": None,
                         "varkw": None,
                         "kwonlyargs": [],
                         "kwonlydefaults": [],
                     },
                     "Terminate the server.")
             return {"status": "ok", "ret": doc}
         elif obj["action"] == "call":
             logger.debug("calling %s", _PrettyPrintCall(obj))
             if (self.builtin_terminate and obj["name"] ==
                     "terminate"):
                 self._terminate_request.set()
                 return {"status": "ok", "ret": None}
             else:
                 method = getattr(target, obj["name"])
                 ret = method(*obj["args"], **obj["kwargs"])
                 if inspect.iscoroutine(ret):
                     ret = await ret
                 return {"status": "ok", "ret": ret}
         else:
             raise ValueError("Unknown action: {}"
                              .format(obj["action"]))
     except asyncio.CancelledError:
         raise
     except:
         return {
             "status": "failed",
             "exception": current_exc_packed()
         }
     finally:
         if self._noparallel is not None:
             self._noparallel.release()
コード例 #19
0
ファイル: thread.py プロジェクト: 343829084/curio
def AWAIT(coro):
    '''
    Await for a coroutine in an asynchronous thread.  If coro is
    not a proper coroutine, this function acts a no-op, returning coro.
    '''
    if not iscoroutine(coro):
        return coro

    if hasattr(_locals, 'thread'):
        return _locals.thread.AWAIT(coro)
    else:
        raise errors.AsyncOnlyError('Must be used as async')
コード例 #20
0
ファイル: rpc.py プロジェクト: smurfix/DaBroker
def coro_wrapper(proc, *a,**k):
	"""\
		This code is responsible for turning whatever callable you pass in
		into a "yield from"-style coroutine.
		"""
	did_call = False
	if inspect.iscoroutinefunction(proc):
		proc = proc(*a,**k)
	if inspect.isawaitable(proc):
		return (yield from proc.__await__())
	if inspect.iscoroutine(proc):
		return (yield from proc)
	return proc(*a,**k)
コード例 #21
0
ファイル: argmethod.py プロジェクト: vijos/vj4
def invoke_by_args():
  import argparse
  import asyncio
  import coloredlogs
  import inspect
  import pprint
  coloredlogs.install(fmt='[%(levelname).1s %(asctime)s %(module)s:%(lineno)d] %(message)s',
                      datefmt='%y%m%d %H:%M:%S')
  parser = argparse.ArgumentParser()
  subparsers = parser.add_subparsers(dest='')
  for name, method in _methods.items():
    subparser = subparsers.add_parser(name)
    argcount = method.__code__.co_argcount
    num_defaults = len(method.__defaults__) if method.__defaults__ else 0
    argoffset = argcount - num_defaults
    for index, argname in enumerate(method.__code__.co_varnames[:argcount]):
      if index < argoffset:
        subparser.add_argument(argname, type=method.__annotations__[argname])
      elif argname in method.__annotations__:
        subparser.add_argument(argname,
                               type=method.__annotations__[argname],
                               nargs='?',
                               default=method.__defaults__[index - argoffset])
  args = parser.parse_args(options.leftovers)
  name = getattr(args, '')
  delattr(args, '')
  if not name:
    parser.print_help()
  else:
    loop = asyncio.get_event_loop()
    loop.run_until_complete(db.init())
    try:
      result = _methods[name](**vars(args))
      if inspect.iscoroutine(result):
        result = loop.run_until_complete(result)
      if options.pretty:
        print_func = pprint.pprint
      else:
        print_func = lambda x: print(x) if x is not None else None
      if hasattr(result, '__aiter__'):
        async def aloop():
          async for entry in result:
            print_func(entry)

        loop.run_until_complete(aloop())
      else:
        print_func(result)
    except KeyboardInterrupt:
      pass
    finally:
      loop.set_exception_handler(lambda loop, context: None)
コード例 #22
0
ファイル: application.py プロジェクト: songww/webpy
    async def _delegate(self, f, fvars, args=[]):
        async def handle_class(cls):
            meth = web.ctx.method
            if meth == "HEAD" and not hasattr(cls, meth):
                meth = "GET"
            if not hasattr(cls, meth):
                raise web.nomethod(cls)
            tocall = getattr(cls(), meth)
            if iscoroutinefunction(tocall):
                return await tocall(*args)
            return tocall(*args)

        if f is None:
            logger.getChild("application._delegate").debug("fn(%s) not found.", f)
            raise self.notfound()
        elif isinstance(f, application):
            logger.getChild("application._delegate").debug("calling handle_with_processors")
            return await f.handle_with_processors()
        elif iscoroutinefunction(f):
            logger.getChild("application._delegate").debug("awaiting coroutine function.")
            return await f()
        elif iscoroutine(f):
            logger.getChild("application._delegate").debug("awaiting coroutine.")
            return await f
        elif isclass(f):
            logger.getChild("application._delegate").debug("calling class %s.", f)
            return await handle_class(f)
        elif isinstance(f, string_types):
            if f.startswith("redirect "):
                url = f.split(" ", 1)[1]
                if web.ctx.method == "GET":
                    x = web.ctx.scope.get("query_string", "")
                    if x:
                        url = "?".join([url, x.decode("utf8")])
                logger.getChild("application._delegate").debug("%s to %s.", f, url)
                raise web.redirect(url)
            elif "." in f:
                mod, cls = f.rsplit(".", 1)
                mod = __import__(mod, None, None, [""])
                cls = getattr(mod, cls)
            else:
                cls = fvars[f]
            logger.getChild("application._delegate").debug("calling class %s", cls)
            return await handle_class(cls)
        elif callable(f):
            logger.getChild("application._delegate").debug("callable object %s", f)
            return f()
        else:
            logger.getChild("application._delegate").debug("%s not found.", f)
            return self.notfound()
コード例 #23
0
	def is_awaitable(obj):
		# There is no single method which can answer in any case, should wait or not - so need to create one
		# for the suspected cases : func, coro, gen-coro, future,
		#                           class with sync __call__, class with async __call__,
		#                           sync method, async method
		if inspect.isawaitable(obj) or inspect.iscoroutinefunction(obj) or inspect.iscoroutine(obj):
			return True
		elif inspect.isgeneratorfunction(obj):
			return True
		elif CallChain.is_user_defined_class(obj):
			if hasattr(obj, '__call__'):
				return CallChain.is_awaitable(obj.__call__)
			return False
		else:
			return False
コード例 #24
0
ファイル: meta.py プロジェクト: 343829084/curio
def instantiate_coroutine(corofunc, *args, **kwargs):
    '''
    Try to instantiate a coroutine. If corofunc is already a coroutine,
    we're done.  If it's a coroutine function, we call it inside an
    async context with the given arguments to create a coroutine.  If
    it's not a coroutine, we call corofunc(*args, **kwargs) and hope
    for the best.
    '''
    if inspect.iscoroutine(corofunc) or inspect.isgenerator(corofunc):
        return corofunc

    if not iscoroutinefunction(corofunc):
        coro = corofunc(*args, **kwargs)
        if not inspect.iscoroutine(coro):
            raise TypeError('Could not create coroutine from %s' % corofunc)
        return coro

    async def context():
        return corofunc(*args, **kwargs)

    try:
        context().send(None)
    except StopIteration as e:
        return e.value
コード例 #25
0
ファイル: loop.py プロジェクト: srossross/uvio
    def tick(self):

        self.handle_exceptions()

        if not self.ready:
            # Don't let idle block the loop from exiting
            # There should be other handdles blocking exiting if
            # there is nothing ready
            self.unref_ticker()
            return
        coroutine_or_func, future = self.ready.popitem()

        if inspect.iscoroutine(coroutine_or_func):
            process_until_await(self, future, coroutine_or_func)
        else:
            coroutine_or_func()
コード例 #26
0
ファイル: spider.py プロジェクト: wangybnet/wsp
 async def start_requests(cls, spiders, start_urls, *, middleware=None):
     try:
         res = []
         for spider in spiders:
             for r in spider.start_requests(start_urls):
                 if inspect.iscoroutine(r):
                     r = await r
                 if r:
                     res.append(r)
         if middleware:
             res = await cls._handle_start_requests(res, middleware)
     except Exception:
         log.warning("Unexpected error occurred when generating start requests", exc_info=True)
         return ()
     else:
         return res
コード例 #27
0
ファイル: loop.py プロジェクト: srossross/uvio
    def next_tick(self, callback, *args, **kwargs):
        """
        Once the current event loop turn runs to completion,
        call the callback or coroutine function::

            loop.next_tick(callback)


        """
        if inspect.iscoroutinefunction(callback):
            raise Exception("Did you mean ot create a coroutine (got: {})".format(callback))

        if not inspect.iscoroutine(callback):
            callback = partial(callback, *args, **kwargs)

        self.ready[callback] = None
コード例 #28
0
ファイル: __init__.py プロジェクト: wheresaddie/opentrons
async def health(request: web.Request) -> web.Response:
    static_paths = ['/logs/serial.log', '/logs/api.log']
    # This conditional handles the case where we have just changed the
    # use protocol api v2 feature flag, so it does not match the type
    # of hardware we're actually using.
    fw_version = request.app['com.opentrons.hardware'].fw_version
    if inspect.iscoroutine(fw_version):
        fw_version = await fw_version

    res = {
        'name': config.name(),
        'api_version': __version__,
        'fw_version': fw_version,
        'logs': static_paths,
        'system_version': config.OT_SYSTEM_VERSION
    }
    return web.json_response(
        headers={'Access-Control-Allow-Origin': '*'},
        body=json.dumps(res))
コード例 #29
0
def determine_object_type(obj):
    if inspect.ismodule(obj):
        return 'Module', obj.__str__()
    elif inspect.isclass(obj):
        return 'Class', obj.__str__()
    elif inspect.ismethod(obj):
        return 'Method', obj.__str__()
    elif inspect.isfunction(obj):
        return 'Function', obj.__str__()
    elif inspect.isgeneratorfunction(obj):
        return 'Generator Function', obj.__str__()
    elif inspect.isgenerator(obj):
        return 'Generator', obj.__str__()
    elif inspect.iscoroutinefunction(obj):
        return 'Coroutine Function', obj.__str__()
    elif inspect.iscoroutine(obj):
        return 'Coroutine', obj.__str__()
    elif inspect.isawaitable(obj):
        return 'Awaitable', obj.__str__()
    elif inspect.istraceback(obj):
        return 'Traceback', obj.__str__()
    elif inspect.isframe(obj):
        return 'Frame', obj.__str__()
    elif inspect.iscode(obj):
        return 'Code', obj.__str__()
    elif inspect.isbuiltin(obj):
        return 'Builtin', obj.__str__()
    elif inspect.isroutine(obj):
        return 'Routine', obj.__str__()
    elif inspect.isabstract(obj):
        return 'Abstract Base Class', obj.__str__()
    elif inspect.ismethoddescriptor(obj):
        return 'Method Descriptor', obj.__str__()
    elif inspect.isdatadescriptor(obj):
        return 'Data Descriptor', obj.__str__()
    elif inspect.isgetsetdescriptor(obj):
        return 'Getset Descriptor', obj.__str__()
    elif inspect.ismemberdescriptor(obj):
        return 'Member Descriptor', obj.__str__()
    elif inspect.isbuiltin(obj):
        return type(obj), obj.__str__()
    else:
        return type(obj), obj.__str__()
コード例 #30
0
ファイル: monad.py プロジェクト: douglas-raillard-arm/lisa
        def run(_f, args, kwargs):
            call = lambda: _f(*args, **kwargs)
            x = call()
            if inspect.iscoroutine(x):

                def body(state):
                    if inspect.getcoroutinestate(x) == inspect.CORO_CLOSED:
                        _x = call()
                    else:
                        _x = x

                    next_ = lambda: _x.send(None)
                    while True:
                        try:
                            future = next_()
                        except StopIteration as e:
                            val = e.value
                            break
                        else:
                            assert isinstance(future, cls)
                            try:
                                val, state = future._f(state)
                            except Exception as e:
                                # We need an intermediate variable here, since
                                # "e" is not really bound in this scope.
                                excep = e
                                next_ = lambda: _x.throw(excep)
                            else:
                                next_ = lambda: _x.send(val)

                    if isinstance(val, cls):
                        return val._f(state)
                    else:
                        return (val, state)

                val = cls.from_f(body, name=f.__qualname__)
            else:
                if isinstance(x, cls):
                    val = x
                else:
                    val = cls.pure(x)

            return val
コード例 #31
0
    def build(self):
        fn = WrappedFunction.find_original(self.inner)

        fn_of_protocol = getattr(self.protocol.proto, fn.__name__)
        if hasattr(fn_of_protocol, '__wf'):
            fn_of_protocol = getattr(fn_of_protocol, '__wf')

        def wrapper(me, *args, **kwargs):
            inner_object = me.__inner
            inner_ctx = me.__ctx

            caller = sys._getframe(1)
            (args, kwargs, bind1) = self.wrap_arguments(
                lambda n: ArgumentExecutionContext(fn_of_protocol, caller, n),
                (inner_object, *args), kwargs)
            if isinstance(self.inner, WrappedFunction):
                (args, kwargs, bind2) = self.inner.wrap_arguments(
                    lambda n: ProtocolArgumentExecutionContext(
                        self, n, inner_object, inner_ctx), args, kwargs)
            ret = fn(*args, **kwargs)
            if isinstance(self.inner, WrappedFunction):
                ret = self.inner.wrap_return(
                    ret, bind2,
                    ProtocolReturnExecutionContext(self, ResponsibilityType.IN,
                                                   inner_object, inner_ctx))
            return self.wrap_return(
                ret, bind1,
                ProtocolReturnExecutionContext(self, ResponsibilityType.OUT,
                                               inner_object, inner_ctx))

        async def async_wrapper(*args, **kwargs):
            raise AssertionError("Not correctly implemented see wrapper")

        if inspect.iscoroutine(self.inner):
            w = async_wrapper
        else:
            w = wrapper

        setattr(w, '__wrapped__', fn)
        setattr(w, '__name__', fn.__name__)
        setattr(w, '__signature__', self.signature)
        setattr(w, '__wf', self)
        return w
コード例 #32
0
    async def get_response(self,
                           *,
                           timeout: Union[int, float] = 0,
                           mark_read: bool = False,
                           filters: Filter = None) -> RawMessage:
        """\nGets the next message that responds to a previous one.

        Parameters:
            timeout (``int`` | ``float``, *optional*):
                Timeout for waiting.
                If present this will override conversation timeout

            mark_read (``bool``, *optional*):
                marks response as read.

            filters (``pyrogram.filters.Filter``, *optional*):
                filter specific response.

        Returns:
            On success, the recieved Message is returned.
        """
        if self._count >= self._limit:
            raise _MsgLimitReached
        queue = _CONV_DICT[(self._chat_id, self._client)]
        if isinstance(queue, tuple):
            queue = queue[1]
        timeout = timeout or self._timeout
        start = time.time()
        while True:
            diff = time.time() - start
            response_ = await asyncio.wait_for(queue.get(),
                                               max(0.1, timeout - diff))
            if filters and callable(filters):
                found = filters(self._client, response_)
                if inspect.iscoroutine(found):
                    found = await found
                if not found:
                    continue
            break
        self._count += 1
        if mark_read:
            await self.mark_read(response_)
        return response_
コード例 #33
0
ファイル: wrappedclass.py プロジェクト: CodeSteak/untypy
    def build(self):
        fn = self.inner
        name = fn.__name__

        def wrapper_cls(*args, **kwargs):
            caller = sys._getframe(1)
            (args, kwargs, bindings) = self.wrap_arguments(
                lambda n: ArgumentExecutionContext(
                    self, caller, n, declared=self.declared()), args, kwargs)
            ret = fn(*args, **kwargs)
            return self.wrap_return(ret, bindings,
                                    ReturnExecutionContext(self))

        def wrapper_self(me, *args, **kwargs):
            if name == '__init__':
                me.__return_ctx = None
                me.__inner = self.create_fn()
            caller = sys._getframe(1)
            (args, kwargs, bindings) = self.wrap_arguments(
                lambda n: ArgumentExecutionContext(
                    self, caller, n, declared=self.declared()),
                (me.__inner, *args), kwargs)
            ret = fn(*args, **kwargs)
            if me.__return_ctx is None:
                return self.wrap_return(ret, bindings,
                                        ReturnExecutionContext(self))
            else:
                return self.wrap_return(ret, bindings, me.__return_ctx)

        if inspect.iscoroutine(self.inner):
            raise UntypyAttributeError(
                "Async Functions are currently not supported.")
        else:
            if 'self' in self.checker:
                w = wrapper_self
            else:
                w = wrapper_cls

        setattr(w, '__wrapped__', fn)
        setattr(w, '__name__', fn.__name__)
        setattr(w, '__signature__', self.signature)
        setattr(w, '__wf', self)
        return w
コード例 #34
0
ファイル: decorators.py プロジェクト: Rezam1998/cocotb
    def __init__(self, inst):

        if inspect.iscoroutine(inst):
            self._natively_awaitable = True
        elif inspect.isgenerator(inst):
            self._natively_awaitable = False
        elif sys.version_info >= (3, 6) and inspect.isasyncgen(inst):
            raise TypeError(
                "{} is an async generator, not a coroutine. "
                "You likely used the yield keyword instead of await.".format(
                    inst.__qualname__))
        else:
            raise TypeError(
                "%s isn't a valid coroutine! Did you forget to use the yield keyword?" % inst)
        self._coro = inst
        self.__name__ = "%s" % inst.__name__
        self._started = False
        self._callbacks = []
        self._outcome = None
コード例 #35
0
    def _resolver(source, info: GraphQLResolveInfo, **kwargs):
        strawberry_info = strawberry_info_from_graphql(field, info)
        _check_permissions(source, strawberry_info, **kwargs)

        result = get_result_for_field(
            field, kwargs=kwargs, info=strawberry_info, source=source
        )

        if iscoroutine(result):  # pragma: no cover

            async def await_result(result):
                result = await result
                result = convert_enums_to_values(field, result)
                return result

            return await_result(result)

        result = convert_enums_to_values(field, result)
        return result
コード例 #36
0
 async def process(self, ctx, iprot, oprot):
     args = basePing_args()
     args.read(iprot)
     iprot.readMessageEnd()
     result = basePing_result()
     try:
         ret = self._handler([ctx])
         if inspect.iscoroutine(ret):
             ret = await ret
     except TApplicationException as ex:
         async with self._lock:
             _write_application_exception(ctx,
                                          oprot,
                                          "basePing",
                                          exception=ex)
             return
     except Exception as e:
         async with self._lock:
             _write_application_exception(
                 ctx,
                 oprot,
                 "basePing",
                 ex_code=TApplicationExceptionType.INTERNAL_ERROR,
                 message=str(e))
         raise
     async with self._lock:
         try:
             oprot.write_response_headers(ctx)
             oprot.writeMessageBegin('basePing', TMessageType.REPLY, 0)
             result.write(oprot)
             oprot.writeMessageEnd()
             oprot.get_transport().flush()
         except TTransportException as e:
             # catch a request too large error because the TMemoryOutputBuffer always throws that if too much data is written
             if e.type == TTransportExceptionType.REQUEST_TOO_LARGE:
                 raise _write_application_exception(
                     ctx,
                     oprot,
                     "basePing",
                     ex_code=TApplicationExceptionType.RESPONSE_TOO_LARGE,
                     message=e.message)
             else:
                 raise e
コード例 #37
0
ファイル: _page.py プロジェクト: nonomal/playwright-python
 async def call(self, func: Callable) -> None:
     try:
         frame = from_channel(self._initializer["frame"])
         source = dict(context=frame._page.context, page=frame._page, frame=frame)
         if self._initializer.get("handle"):
             result = func(source, from_channel(self._initializer["handle"]))
         else:
             func_args = list(map(parse_result, self._initializer["args"]))
             result = func(source, *func_args)
         if inspect.iscoroutine(result):
             result = await result
         await self._channel.send("resolve", dict(result=serialize_argument(result)))
     except Exception as e:
         tb = sys.exc_info()[2]
         asyncio.create_task(
             self._channel.send(
                 "reject", dict(error=dict(error=serialize_error(e, tb)))
             )
         )
コード例 #38
0
    def _check_process(self, process):
        if not (inspect.isgeneratorfunction(process)
                or inspect.iscoroutinefunction(process)):
            if inspect.isgenerator(process) or inspect.iscoroutine(process):
                warnings.warn(
                    "instead of generators, use generator functions as processes; "
                    "this allows the simulator to be repeatedly reset",
                    DeprecationWarning,
                    stacklevel=3)

                def wrapper():
                    yield from process

                return wrapper
            else:
                raise TypeError(
                    "Cannot add a process {!r} because it is not a generator function"
                    .format(process))
        return process
コード例 #39
0
 async def callback(transport):
     iprot = protocol_factory.get_protocol(transport)
     ctx = iprot.read_request_headers()
     mname, _, _ = iprot.readMessageBegin()
     if mname != op:
         iprot.skip(TType.STRUCT)
         iprot.readMessageEnd()
         raise TApplicationException(
             TApplicationExceptionType.UNKNOWN_METHOD)
     req = Album()
     req.read(iprot)
     iprot.readMessageEnd()
     try:
         ret = method([ctx, req])
         if inspect.iscoroutine(ret):
             await ret
     except:
         traceback.print_exc()
         sys.exit(1)
コード例 #40
0
async def test_predict(mlserver_runtime: InferenceRuntime, inference_request: InferenceRequest):
    # NOTE: pytest-cases doesn't wait for async fixtures
    # TODO: Raise issue in pytest-cases repo
    mlserver_runtime = await mlserver_runtime
    res = await mlserver_runtime.predict(inference_request)

    assert len(res.outputs) == 1

    pipeline_input = to_ndarray(inference_request.inputs[0])
    custom_model = copy.copy(mlserver_runtime._model)
    # Ensure direct call to class does not try to do remote
    custom_model.set_remote(False)
    expected_output = custom_model(payload=pipeline_input)
    if iscoroutine(expected_output):
        expected_output = await expected_output

    pipeline_output = res.outputs[0].data

    assert expected_output.tolist() == pipeline_output
コード例 #41
0
def _call(__klein_instance__, __klein_f__, *args, **kwargs):
    """
    Call C{__klein_f__} with the given C{*args} and C{**kwargs}.

    Insert C{__klein_instance__} as the first positional argument to
    C{__klein_f__} if C{__klein_f__} is not decorated with
    L{klein._decorators.bindable}.

    @return: The result of C{__klein_f__}; additionally, if C{__klein_f__}
        returns a coroutine, instead return the Deferred created by calling
        C{ensureDeferred} on it.
    """
    if __klein_instance__ is not None or getattr(__klein_f__,
                                                 "__klein_bound__", False):
        args = (__klein_instance__, ) + args
    result = __klein_f__(*args, **kwargs)
    if iscoroutine(result):
        result = ensureDeferred(result)
    return result
コード例 #42
0
    async def _get_attribute_values(
        self,
        obj: GetAttrObjectT,
        attribute_name: str,
        op: typing.Callable[[typing.Any], typing.Any],
    ) -> typing.List[typing.Any]:
        try:
            attr = getattr(obj, attribute_name)
            if inspect.iscoroutine(attr):
                attr = await attr
        except AttributeError:
            raise UnknownAttribute(attribute_name)

        try:
            values = op(attr)
        except TypeError:
            raise InvalidOperator(attribute_name)

        return self._to_list(values)
コード例 #43
0
    async def get_prefixes(bot, message):
        mentions = [f"<@{bot.me.id}> ", f"<@!{bot.me.id}> "]

        if callable(prefix_provider):
            prefixes = prefix_provider(bot, message)
            if inspect.iscoroutine(prefixes) or isinstance(
                    prefixes, asyncio.Future):
                prefixes = await prefixes
        else:
            prefixes = prefix_provider

        if isinstance(prefixes, str):
            return mentions + [prefixes]
        elif isinstance(prefixes, typing.Iterable):
            return mentions + list(prefixes)
        elif prefixes is None:
            return mentions
        else:
            return mentions + [prefix async for prefix in prefixes]
コード例 #44
0
    def _resolver(source, info: Info, **kwargs):
        _check_permissions(source, info, **kwargs)

        result = get_result_for_field(field,
                                      kwargs=kwargs,
                                      info=info,
                                      source=source)

        if iscoroutine(result):  # pragma: no cover

            async def await_result(result):
                result = await result
                result = convert_enums_to_values(field, result)
                return result

            return await_result(result)

        result = convert_enums_to_values(field, result)
        return result
コード例 #45
0
ファイル: _checkers.py プロジェクト: gordol/icontract
def _assert_preconditions(preconditions: List[List[Contract]],
                          resolved_kwargs: Mapping[str, Any],
                          func: CallableT) -> Optional[BaseException]:
    """Assert that the preconditions of a sync function hold."""
    exception = None  # type: Optional[BaseException]

    # Assert the preconditions in groups. This is necessary to implement "require else" logic when a class
    # weakens the preconditions of its base class.

    for group in preconditions:
        exception = None

        for contract in group:
            assert exception is None, "No exception as long as pre-condition group is satisfiable."

            condition_kwargs = select_condition_kwargs(
                contract=contract, resolved_kwargs=resolved_kwargs)

            if inspect.iscoroutinefunction(contract.condition):
                raise ValueError(
                    "Unexpected coroutine (async) condition {} for a sync function {}."
                    .format(contract.condition, func))

            check = contract.condition(**condition_kwargs)

            if inspect.iscoroutine(check):
                raise ValueError(
                    "Unexpected coroutine resulting from the condition {} for a sync function {}."
                    .format(contract.condition, func))

            if not_check(check=check, contract=contract):
                exception = _create_violation_error(
                    contract=contract,
                    resolved_kwargs=resolved_kwargs,
                    condition_kwargs=condition_kwargs)
                break

        # The group of preconditions was satisfied, no need to check the other groups.
        if exception is None:
            break

    return exception
コード例 #46
0
ファイル: core.py プロジェクト: lojack5/wxtrio
 def DynamicBind(self,
                 wx_window,
                 wx_event_binder,
                 handler,
                 source=None,
                 id=wx.ID_ANY,
                 id2=wx.ID_ANY):
     """Binds an event handler to a wx Event callback.  Automatically detects if the handler
        is async or sync, and bind appropriately.
     """
     if inspect.iscoroutinefunction(handler):
         # 'async def' function that has not been called
         self._queue_cleanup(wx_window)
         self.window_bindings[wx_window].event_handlers[
             wx_event_binder.typeId].append(handler)
         self._BindSync(wx_window,
                        wx_event_binder,
                        lambda event: self.OnEvent(event, wx_window,
                                                   wx_event_binder.typeId),
                        source=source,
                        id=id,
                        id2=id2)
     elif inspect.iscoroutine(handler):
         # 'async def' function that has been called and returned an awaitable object
         raise TypeError(
             'Event handler is an awaitable object returned from an async function.  Do not call the async function.'
         )
     elif inspect.isawaitable(handler):
         # Some other awaitable object
         raise TypeError(
             'Event handler is an awaitable object.  Pass either a function or an async function.'
         )
     elif not callable(handler):
         raise TypeError('Event handler is not callable.')
     else:
         # Sync event handler
         self._BindSync(wx_window,
                        wx_event_binder,
                        handler,
                        source=source,
                        id=id,
                        id2=id2)
コード例 #47
0
    def compute(context, input_defs) -> Generator[Output, None, None]:
        kwargs = {}
        for input_name in input_names:
            kwargs[input_name] = input_defs[input_name]

        if (inspect.isgeneratorfunction(fn) or inspect.isasyncgenfunction(fn)
                or inspect.iscoroutinefunction(fn)):
            # safe to execute the function, as doing so will not immediately execute user code
            result = fn(context, **kwargs) if context_arg_provided else fn(
                **kwargs)
            if inspect.iscoroutine(result):
                return _coerce_async_solid_to_async_gen(
                    result, context, output_defs)
            # already a generator
            return result
        else:
            # we have a regular function, do not execute it before we are in an iterator
            # (as we want all potential failures to happen inside iterators)
            return _coerce_solid_compute_fn_to_iterator(
                fn, output_defs, context, context_arg_provided, kwargs)
コード例 #48
0
ファイル: eventbus.py プロジェクト: jadbin/xpaw
 async def send(self, event, **kwargs):
     if event not in self._refs:
         return
     del_list = []
     for i in self._refs[event]:
         f = self._refs[event][i]()
         if f is None:
             del_list.append(i)
         else:
             try:
                 res = f(**kwargs)
                 if inspect.iscoroutine(res):
                     await res
             except CancelledError:
                 raise
             except Exception:
                 log.warning("Failed to send the event", exc_info=True)
     for i in del_list:
         del self._refs[event][i]
     del del_list
コード例 #49
0
def sync(f):
    if inspect.iscoroutine(f):
        try:
            loop = asyncio.get_event_loop()
        except RuntimeError:
            loop = asyncio.new_event_loop()
        return loop.run_until_complete(f)

    if inspect.iscoroutinefunction(f):
        return _wrap_sync(f)

    if callable(f):
        with suppress(AttributeError):
            if inspect.iscoroutinefunction(getattr(f, '__call__')):
                return _wrap_sync(f)
        return f

    raise ValueError(
        'Can only synchronize coroutine callables (`async def`) or coroutines (values returned by `async def`), or pass through synchronous callables, but "%s" was given.'
        % f)
コード例 #50
0
    async def test_voice_ban_user_left_guild(self, apply_infraction_mock,
                                             post_infraction_mock, _):
        """Should voice ban user that left the guild without throwing an error."""
        infraction = {"foo": "bar"}
        post_infraction_mock.return_value = {"foo": "bar"}

        user = MockUser()
        await self.cog.voiceban(self.cog, self.ctx, user, reason=None)
        post_infraction_mock.assert_called_once_with(self.ctx,
                                                     user,
                                                     "voice_ban",
                                                     None,
                                                     active=True)
        apply_infraction_mock.assert_called_once_with(self.cog, self.ctx,
                                                      infraction, user, ANY)

        # Test action
        action = self.cog.apply_infraction.call_args[0][-1]
        self.assertTrue(inspect.iscoroutine(action))
        await action
コード例 #51
0
async def deepawait_or_sync(
    value_or_function_or_coroutine: Union[Any, FunctionType, Coroutine, ],
    *args,
    **kwargs,
) -> Any:
    """双重await,lambda"""
    if callable(value_or_function_or_coroutine):
        # 第一次调用一个协程,会返回一个awaitable
        # awaitable不可调用
        result = value_or_function_or_coroutine(*args, **kwargs)

        while iscoroutine(result) or callable(result):
            if callable(result):
                result = result()
            else:
                result = await result

        return result

    return value_or_function_or_coroutine
コード例 #52
0
    def make_request(self, response_mapping: ResponseMapping,
                     api_request: ApiRequest) -> DeserializedResponse:
        request_hooks: RequestHooks = self._configuration.hooks.get(
            Hook.request, [])
        for request_hook in request_hooks:
            api_request = request_hook(api_request)

        result = self._client.call_api(api_request)

        if inspect.iscoroutine(result):

            async def _wrap_coroutine():
                api_response: ApiResponse = await result
                return self._handle_result(response_mapping, api_request,
                                           api_response)

            return _wrap_coroutine()

        return self._handle_result(response_mapping, api_request,
                                   cast(ApiResponse, result))
コード例 #53
0
ファイル: pod.py プロジェクト: sogou-nyx/os-aio-pod
    def _create_bean(self, loop, kw):
        obj, label, kwargs = kw
        instance = None
        coro = obj
        idx = 1 if not self._beans else list(self._beans.keys())[-1] + 1
        context = BeanContext(self, idx, label)

        if iscoroutine(obj):
            pass
        elif iscoroutinefunction(obj):
            coro = obj(**kwargs)
        elif (isclass(obj) and hasattr(obj, "__call__")
              and iscoroutinefunction(obj.__call__)):
            instance = obj(context)
            coro = instance(**kwargs)
        else:
            raise TypeError(f"Invalid type {type(obj)}")

        context.instance = instance
        return Bean(context, coro, loop=self._loop)
コード例 #54
0
ファイル: steps.py プロジェクト: pcanto-hopeit/hopeit.engine
async def _invoke_step(
        *, payload: Optional[EventPayload], func: Callable,
        context: EventContext, disable_spawn: bool,
        **kwargs) -> AsyncGenerator[Optional[EventPayload], None]:
    """
    Invokes step handler method
    """
    func_res = func(payload, context, **kwargs)
    if inspect.iscoroutine(func_res):
        yield await func_res
    elif isinstance(func_res, AsyncGenerator):  # pylint: disable=isinstance-second-argument-not-valid-type
        if disable_spawn:
            raise NotImplementedError(
                "`Spawn[...]` only supported in initial step."
                " Cannot execute `{func.__name__}`."
                " Insert `SHUFFLE` step after spawn event.")
        async for res in func_res:
            yield res
    else:
        yield func_res
コード例 #55
0
ファイル: http.py プロジェクト: thilp/aiopykube
 def __init__(
     self,
     config: KubeConfig,
     *,
     timeout: float = DEFAULT_HTTP_TIMEOUT,
     session: Optional[aiohttp.ClientSession] = None,
     default_headers: Optional[Dict[str, str]] = None,
 ) -> None:
     if inspect.iscoroutine(config):
         raise ValueError(f"should be awaited: {config.__qualname__}")
     if default_headers is None:
         default_headers = {}
     self.config = config
     self.timeout = timeout
     self.session = session
     self.kwargs: Optional[Dict[str, Any]] = None
     self.default_headers = {
         "User-Agent": f"aiopykube/{__version__}",
         **default_headers,
     }
コード例 #56
0
def _is_coro(obj: Any) -> bool:
    """
    Small helper function to test an object against :meth:`inspect.iscoroutinefunction` and
    :meth:`inspect.iscoroutine` with a try/except to protect against a missing ``_is_coroutine`` attribute
    causing an error.
    
    :param Any obj: The object to check
    :return bool is_coro: ``True`` if ``obj`` is a coroutine function or a coroutine. Otherwise ``False``.
    """
    try:
        if inspect.iscoroutinefunction(obj) or inspect.iscoroutine(obj):
            return True
        return False
    except (AttributeError, KeyError) as e:
        # iscoroutine / iscoroutinefunction can sometimes throw a KeyError / AttributeError when checking
        # for the '_is_coroutine' key / attribute. If we encounter such an error, it's probably not a coroutine.
        log.debug(
            "exception while checking if object '%s' is coroutine in asyncx._is_coro: %s %s",
            obj, type(e), str(e))
    return False
コード例 #57
0
    async def test_run_async(self, async_engine):
        async def test_meth(async_driver_connection):
            # there's no method that's guaranteed to be on every
            # driver, so just stringify it and compare that to the
            # outside
            return str(async_driver_connection)

        def run_sync_to_async(connection):
            connection_fairy = connection.connection
            async_return = connection_fairy.run_async(
                lambda driver_connection: test_meth(driver_connection))
            assert not stdlib_inspect.iscoroutine(async_return)
            return async_return

        async with async_engine.connect() as conn:
            driver_connection = (await
                                 conn.get_raw_connection()).driver_connection
            res = await conn.run_sync(run_sync_to_async)
            assert not stdlib_inspect.iscoroutine(res)
            eq_(res, str(driver_connection))
コード例 #58
0
def _CallAndUpdateTrace(component, args, component_trace, treatment='class',
                        target=None):
  """Call the component by consuming args from args, and update the FireTrace.

  The component could be a class, a routine, or a callable object. This function
  calls the component and adds the appropriate action to component_trace.

  Args:
    component: The component to call
    args: Args for calling the component
    component_trace: FireTrace object that contains action trace
    treatment: Type of treatment used. Indicating whether we treat the component
        as a class, a routine, or a callable.
    target: Target in FireTrace element, default is None. If the value is None,
        the component itself will be used as target.
  Returns:
    component: The object that is the result of the callable call.
    remaining_args: The remaining args that haven't been consumed yet.
  """
  if not target:
    target = component
  filename, lineno = inspectutils.GetFileAndLine(component)
  metadata = decorators.GetMetadata(component)
  fn = component.__call__ if treatment == 'callable' else component
  parse = _MakeParseFn(fn, metadata)
  (varargs, kwargs), consumed_args, remaining_args, capacity = parse(args)
  component = fn(*varargs, **kwargs)
  if inspect.iscoroutine(component):
    component = asyncio.run(component)

  if treatment == 'class':
    action = trace.INSTANTIATED_CLASS
  elif treatment == 'routine':
    action = trace.CALLED_ROUTINE
  else:
    action = trace.CALLED_CALLABLE
  component_trace.AddCalledComponent(
      component, target, consumed_args, filename, lineno, capacity,
      action=action)

  return component, remaining_args
コード例 #59
0
ファイル: processors.py プロジェクト: Tiendil/aflow
    async def __call__(self):
        if self.next_handler + 1 >= len(self.handlers):
            return

        self.next_handler += 1

        handler = self.handlers[self.next_handler]

        if inspect.iscoroutinefunction(handler):
            await handler(self, self.context)
        else:
            sync_handlers_stack = [handler(self, self.context)]

            while True:
                last_sync_handler = sync_handlers_stack[-1]

                if last_sync_handler is None:
                    sync_handlers_stack.pop()
                    break # it was last handler result
                elif inspect.iscoroutine(last_sync_handler):
                    sync_handlers_stack.pop()
                    await last_sync_handler
                    break
                else:
                    try:
                        sync_processor = next(last_sync_handler)
                    except StopIteration:
                        break

                    try:
                        next_handler = next(sync_processor)
                        sync_handlers_stack.append(next_handler)
                    except StopIteration:
                        pass

            for sync_handler in reversed(sync_handlers_stack):
                try:
                    next(sync_handler)
                except StopIteration:
                    pass
コード例 #60
0
ファイル: debug.py プロジェクト: M-o-a-T/qbroker
    async def run_eval(self, code=None, mode="eval", **args):
        """\
            Evaluate @code (string). @mode may be 'exec', 'single' or 'eval'/'vars'
            (default: 'eval').
            All other arguments are used as local variables.
            Non-local variables are persistent. The result is returned.

            The mode 'vars' behaves like 'eval' but applies vars() to the result.
            """
        do_vars = False
        if mode == "vars":
            mode = "eval"
            do_vars = True

        code = compile(code, "(debug)", mode)
        loc = args.copy()

        self.env['broker'] = self.broker()
        try:
            res = eval(code, self.env, loc)
            if inspect.iscoroutine(res):
                res = await res
        finally:
            del self.env['broker']

        for k, v in loc.items():
            if k not in args:
                self.env[k] = v
        if do_vars:
            try:
                r = vars(res)
            except TypeError:
                r = {}
                for k in dir(res):
                    v = getattr(res, k)
                    if not callable(v):
                        r[k] = v
            r['__obj__'] = str(res)
            res = r
        return res