python类iscoroutinefunction()的实例源码

loop.py 文件源码 项目:uvio 作者: srossross 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
handler.py 文件源码 项目:calm 作者: bagrat 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def _handle_request(self, handler_def, **kwargs):
        """A generic HTTP method handler."""
        if not handler_def:
            raise MethodNotAllowedError()

        handler = handler_def.handler
        kwargs.update(self._get_query_args(handler_def))
        self._cast_args(handler, kwargs)
        self._parse_and_update_body(handler_def)
        if inspect.iscoroutinefunction(handler):
            resp = await handler(self.request, **kwargs)
        else:
            self.log.warning("'%s' is not a coroutine!", handler_def.handler)
            resp = handler(self.request, **kwargs)

        if resp:
            self._write_response(resp, handler_def)
decorator.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def create(cls, obj, body, evaldict, defaults=None,
               doc=None, module=None, addsource=True, **attrs):
        """
        Create a function from the strings name, signature and body.
        evaldict is the evaluation dictionary. If addsource is true an
        attribute __source__ is added to the result. The attributes attrs
        are added, if any.
        """
        if isinstance(obj, str):  # "name(signature)"
            name, rest = obj.strip().split('(', 1)
            signature = rest[:-1]  # strip a right parens
            func = None
        else:  # a function
            name = None
            signature = None
            func = obj
        self = cls(func, name, signature, defaults, doc, module)
        ibody = '\n'.join('    ' + line for line in body.splitlines())
        caller = evaldict.get('_call_')  # when called from `decorate`
        if caller and iscoroutinefunction(caller):
            body = ('async def %(name)s(%(signature)s):\n' + ibody).replace(
                'return', 'return await')
        else:
            body = 'def %(name)s(%(signature)s):\n' + ibody
        return self.make(body, evaldict, addsource, **attrs)
event.py 文件源码 项目:curious 作者: SunDwarf 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def add_event(self, func, name: str = None):
        """
        Add an event to the internal registry of events.

        :param name: The event name to register under.
        :param func: The function to add.
        """
        if not inspect.iscoroutinefunction(func):
            raise TypeError("Event must be a coroutine function")

        if name is None:
            evs = func.events
        else:
            evs = [name]

        for ev_name in evs:
            logger.debug("Registered event `{}` handling `{}`".format(func, ev_name))
            self.event_listeners.add(ev_name, func)
asynctest.py 文件源码 项目:aioprometheus 作者: claws 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def isawaitable(obj):
    ''' Return True if the object is an awaitable or is a function that
    returns an awaitable.

    This function is used internally by aiotesting.
    '''
    if PY35:
        result = inspect.iscoroutinefunction(obj) or inspect.isawaitable(obj)

    elif PY34:
        result = (isinstance(obj, asyncio.Future) or
                  asyncio.iscoroutine(obj) or
                  hasattr(obj, '__await__'))
    else:
        raise Exception(
            'isawaitable is not supported on Python {}'.format(
                sys.version_info))
    return result
asynctest.py 文件源码 项目:aioprometheus 作者: claws 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _tearDown(self):
        ''' Destroy the event loop '''
        if asyncio.iscoroutinefunction(self.tearDown):
            self.loop.run_until_complete(self.tearDown())
        else:
            self.tearDown()

        if not isinstance(self.loop, asyncio.AbstractEventLoop):
            raise Exception('Invalid event loop: ', self.loop)
        if self.loop.is_running():
            self.loop.stop()
        self.loop.close()
        del self.loop
        asyncio.set_event_loop_policy(None)
        asyncio.set_event_loop(None)

        # By explicitly forcing a garbage collection here,
        # the event loop will report any remaining sockets
        # and coroutines left in the event loop which indicates
        # that further cleanup actions should be implemented
        # in the code under test.
        gc.collect()
__init__.py 文件源码 项目:asyncpg 作者: MagicStack 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _iter_methods(bases, ns):
        for base in bases:
            for methname in dir(base):
                if not methname.startswith('test_'):
                    continue

                meth = getattr(base, methname)
                if not inspect.iscoroutinefunction(meth):
                    continue

                yield methname, meth

        for methname, meth in ns.items():
            if not methname.startswith('test_'):
                continue

            if not inspect.iscoroutinefunction(meth):
                continue

            yield methname, meth
nettirely.py 文件源码 项目:nettirely 作者: 8Banana 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def on_regexp(self, regexp):
        """
        Creates a decorator that registers a regexp command handler.

        The regexp command handler takes as arguments:
            1. The bot instance
            2. The command sender
            3. The command recipient, usually a channel
            4. The match object, for any groups you might wanna extract.

        The regexp is searched, not just matched.
        Your handler might get called multiple times per message,
        depending on the amount of matches.
        """

        regexp = re.compile(regexp)

        def _inner(func):
            if not inspect.iscoroutinefunction(func):
                raise ValueError("You can only register coroutines!")
            self._regexp_callbacks.setdefault(regexp, [])\
                                  .append(func)
            return func
        return _inner
discord_transport.py 文件源码 项目:plumeria 作者: sk89q 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def __getattr__(self, item):
        attr = getattr(self.delegate, item)

        if inspect.iscoroutinefunction(attr) or hasattr(attr,
                                                        "_is_coroutine") and attr._is_coroutine or inspect.iscoroutine(
            attr):
            async def wrapper(*args, **kwargs):
                return self._wrap(await attr(*args, **kwargs))

            return wrapper() if inspect.iscoroutine(attr) else wrapper
        elif inspect.isgeneratorfunction(attr) or inspect.isgenerator(attr):
            def wrapper(*args, **kwargs):
                for entry in attr(*args, **kwargs):
                    yield self._wrap(entry)

            return wrapper if inspect.isgeneratorfunction(attr) else wrapper()
        elif inspect.isfunction(attr):
            def wrapper(*args, **kwargs):
                return self._wrap(attr(*args, **kwargs))

            return wrapper
        else:
            return self._wrap(attr)
__init__.py 文件源码 项目:uninhibited 作者: akatrevorjay 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _call_handler(self, *, handler, args, kwargs, loop=None, start=True, executor=None):
        if loop is None:
            loop = asyncio.get_event_loop()

        if (inspect.iscoroutinefunction(handler) or inspect.isgeneratorfunction(handler)):
            # Get a coro/future
            f = handler(*args, **kwargs)
        else:
            # run_in_executor doesn't support kwargs
            handler = functools.partial(handler, *args, **kwargs)

            # Get result/coro/future
            f = loop.run_in_executor(executor, handler)

        if start:
            # Wrap future in a task, schedule it for execution
            f = asyncio.ensure_future(f, loop=loop)

        # Return a coro that awaits our existing future
        return self._result_tuple(handler, f)
decorator.py 文件源码 项目:flask 作者: bobohope 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def create(cls, obj, body, evaldict, defaults=None,
               doc=None, module=None, addsource=True, **attrs):
        """
        Create a function from the strings name, signature and body.
        evaldict is the evaluation dictionary. If addsource is true an
        attribute __source__ is added to the result. The attributes attrs
        are added, if any.
        """
        if isinstance(obj, str):  # "name(signature)"
            name, rest = obj.strip().split('(', 1)
            signature = rest[:-1]  # strip a right parens
            func = None
        else:  # a function
            name = None
            signature = None
            func = obj
        self = cls(func, name, signature, defaults, doc, module)
        ibody = '\n'.join('    ' + line for line in body.splitlines())
        caller = evaldict.get('_call_')  # when called from `decorate`
        if caller and iscoroutinefunction(caller):
            body = ('async def %(name)s(%(signature)s):\n' + ibody).replace(
                'return', 'return await')
        else:
            body = 'def %(name)s(%(signature)s):\n' + ibody
        return self.make(body, evaldict, addsource, **attrs)
json_resource.py 文件源码 项目:retwist 作者: trustyou 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def render_GET(self, request):
        # type: (Request) -> int
        """
        Get JSON data from json_GET, and render for the client.

        Do not override in sub classes ...
        :param request: Twisted request
        """
        if iscoroutinefunction(self.json_GET):
            coroutine = self.json_GET(request)
            json_def = ensureDeferred(coroutine)  # type: Deferred
        else:
            json_def = maybeDeferred(self.json_GET, request)

        json_def.addCallback(self.send_json_response, request)
        json_def.addErrback(self.handle_failure, request)

        # handle connection failures
        request.notifyFinish().addErrback(self.on_connection_closed, json_def)

        return NOT_DONE_YET
decorator.py 文件源码 项目:yatta_reader 作者: sound88 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def create(cls, obj, body, evaldict, defaults=None,
               doc=None, module=None, addsource=True, **attrs):
        """
        Create a function from the strings name, signature and body.
        evaldict is the evaluation dictionary. If addsource is true an
        attribute __source__ is added to the result. The attributes attrs
        are added, if any.
        """
        if isinstance(obj, str):  # "name(signature)"
            name, rest = obj.strip().split('(', 1)
            signature = rest[:-1]  # strip a right parens
            func = None
        else:  # a function
            name = None
            signature = None
            func = obj
        self = cls(func, name, signature, defaults, doc, module)
        ibody = '\n'.join('    ' + line for line in body.splitlines())
        caller = evaldict.get('_call_')  # when called from `decorate`
        if caller and iscoroutinefunction(caller):
            body = ('async def %(name)s(%(signature)s):\n' + ibody).replace(
                'return', 'return await')
        else:
            body = 'def %(name)s(%(signature)s):\n' + ibody
        return self.make(body, evaldict, addsource, **attrs)
task.py 文件源码 项目:yaz 作者: yaz 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __call__(self, **kwargs):
        """Prepare dependencies and call this Task"""
        start = datetime.datetime.now()
        logger.info("Start task %s", self)
        try:
            if self.plugin_class:
                result = self.func(get_plugin_instance(self.plugin_class), **kwargs)

            else:
                result = self.func(**kwargs)

            if inspect.iscoroutinefunction(self.func):
                assert inspect.iscoroutine(
                    result), "The task is defined as a coroutine function but does not return a coroutine"
                loop = asyncio.get_event_loop()
                if loop.is_closed():
                    loop = asyncio.new_event_loop()
                    asyncio.set_event_loop(loop)
                result = loop.run_until_complete(result)
                loop.close()
        finally:
            stop = datetime.datetime.now()
            logger.info("End task %s after %s", self, stop - start)

        return result
command.py 文件源码 项目:PyPlanet 作者: PyPlanet 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def handle(self, instance, player, argv):
        """
        Handle command parsing and execution.

        :param player: Player object.
        :param argv: Arguments in array
        :type player: pyplanet.apps.core.maniaplanet.models.player.Player
        """
        # Check permissions.
        if self.perms and len(self.perms) > 0:
            # All the given perms need to be matching!
            is_allowed = await asyncio.gather(*[
                instance.permission_manager.has_permission(player, perm) for perm in self.perms
            ])
            if not all(allowed is True for allowed in is_allowed):
                await instance.chat(
                    '$z$sYou are not authorized to use this command!',
                    player.login
                )
                return

        # Strip off the namespace and command.
        paramv = self.get_params(argv)

        # Parse, validate and show errors if any.
        self.parser.parse(paramv)
        if not self.parser.is_valid():
            await instance.gbx.multicall(
                instance.chat('$z$sCommand operation got invalid arguments: {}'.format(', '.join(self.parser.errors)), player),
                instance.chat('$z$s >> {}'.format(self.usage_text), player),
            )
            return

        # We are through. Call our target!
        if iscoroutinefunction(self.target):
            return await self.target(player=player, data=self.parser.data, raw=argv, command=self)
        return self.target(player=player, data=self.parser.data, raw=argv, command=self)
messaging.py 文件源码 项目:CEX.IO-Client-Python3.5 作者: cexioltd 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 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
test_platform.py 文件源码 项目:bottery 作者: rougeth 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_baseengine_not_implemented_calls(method_name):
    """Check if method calls from public API raise NotImplementedError"""
    engine = BaseEngine()
    with pytest.raises(NotImplementedError):
        method = getattr(engine, method_name)
        if inspect.iscoroutinefunction(method):
            await method()
        else:
            method()
__init__.py 文件源码 项目:bottery 作者: rougeth 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_response(self, view, message):
        """
        Get response running the view with await syntax if it is a
        coroutine function, otherwise just run it the normal way.
        """

        if inspect.iscoroutinefunction(view):
            return await view(message)

        return view(message)
base.py 文件源码 项目:poloniex-api 作者: absortium 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def command_operator(func):
    if iscoroutinefunction(func):
        async def async_decorator(self, *args, **kwargs):
            kwargs = apply_defaults(func, *args, **kwargs)
            method, params = self.get_params(func.__name__, **kwargs)

            if method == "post":
                response = await self.api_call(data=params)
            elif method == "get":
                response = await self.api_call(params=params)
            else:
                raise PoloniexError("Not available method '{}'".format(method))

            return self.response_handler(response, command=func.__name__)

        return async_decorator
    else:
        def decorator(self, *args, **kwargs):
            kwargs = apply_defaults(func, *args, **kwargs)
            method, params = self.get_params(func.__name__, **kwargs)

            if method == "post":
                response = self.api_call(data=params)
            elif method == "get":
                response = self.api_call(params=params)
            else:
                raise PoloniexError("Not available method '{}'".format(method))

            return self.response_handler(response, command=func.__name__)

        return decorator
common.py 文件源码 项目:toapy 作者: endreman0 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __get__(desc, obj, cls):
        if obj is None: return desc # no classmethod-style replacement
        attrs = vars(obj)
        if desc.fn.__name__ in attrs:
            return attrs[desc.fn.__name__]

        try:
            fetcher = obj._get
        except AttributeError:
            raise TypeError('TOA object %r must declare _get' % obj) from None
        meth = desc.fn.__get__(obj)
        if inspect.iscoroutinefunction(fetcher):
            @functools.wraps(desc.fn)
            async def wrapper(self, *args, **kwargs):
                url = desc.get_url(args, kwargs)
                json = await self._get(url)
                return meth(json)
        else:
            @functools.wraps(desc.fn)
            def wrapper(self, *args, **kwargs):
                url = desc.get_url(args, kwargs)
                json = self._get(url)
                return meth(json)
        ret = wrapper.__get__(obj)
        attrs[desc.fn.__name__] = ret
        return ret
conftest.py 文件源码 项目:trio 作者: python-trio 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def pytest_pyfunc_call(pyfuncitem):
    if inspect.iscoroutinefunction(pyfuncitem.obj):
        pyfuncitem.obj = trio_test(pyfuncitem.obj)
conftest.py 文件源码 项目:trio 作者: python-trio 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def pytest_pyfunc_call(pyfuncitem):
    if inspect.iscoroutinefunction(pyfuncitem.obj):
        pyfuncitem.obj = trio_test(pyfuncitem.obj)
meta.py 文件源码 项目:asyncqlio 作者: SunDwarf 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def __init__(cls, name, bases, methods):
        coros = {}
        for base in reversed(cls.__mro__):
            coros.update((name, val) for name, val in vars(base).items()
                         if inspect.iscoroutinefunction(val))

        for name, val in vars(cls).items():
            if name in coros and not inspect.iscoroutinefunction(val):
                raise TypeError('Must use async def %s%s' % (name, inspect.signature(val)))
        super().__init__(name, bases, methods)
meta.py 文件源码 项目:asyncqlio 作者: SunDwarf 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def __new__(meta, clsname, bases, attributes):
        if '__init__' in attributes and not inspect.iscoroutinefunction(attributes['__init__']):
            raise TypeError('__init__ must be a coroutine')
        return super().__new__(meta, clsname, bases, attributes)
__init__.py 文件源码 项目:sphinxcontrib-trio 作者: python-trio 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def sniff_options(obj):
    options = set()
    # We walk the __wrapped__ chain to collect properties.
    while True:
        if getattr(obj, "__isabstractmethod__", False):
            options.add("abstractmethod")
        if isinstance(obj, classmethod):
            options.add("classmethod")
        if isinstance(obj, staticmethod):
            options.add("staticmethod")
        # if isinstance(obj, property):
        #     options.add("property")
        # Only check for these if we haven't seen any of them yet:
        if not (options & EXCLUSIVE_OPTIONS):
            if inspect.iscoroutinefunction(obj):
                options.add("async")
            # in some versions of Python, isgeneratorfunction returns true for
            # coroutines, so we use elif
            elif inspect.isgeneratorfunction(obj):
                options.add("for")
            if isasyncgenfunction(obj):
                options.add("async-for")
            # Some heuristics to detect when something is a context manager
            if getattr(obj, "__code__", None) in CM_CODES:
                options.add("with")
            if getattr(obj, "__returns_contextmanager__", False):
                options.add("with")
            if getattr(obj, "__returns_acontextmanager__", False):
                options.add("async-with")
        if hasattr(obj, "__wrapped__"):
            obj = obj.__wrapped__
        elif hasattr(obj, "__func__"):  # for staticmethod & classmethod
            obj = obj.__func__
        else:
            break

    return options
decorator.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def iscoroutinefunction(f):
        return False

# getargspec has been deprecated in Python 3.5
asynctools.py 文件源码 项目:omnic 作者: michaelpb 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def coerce_to_synchronous(func):
    '''
    Given a function that might be async, wrap it in an explicit loop so it can
    be run in a synchronous context.
    '''
    if inspect.iscoroutinefunction(func):
        @functools.wraps(func)
        def sync_wrapper(*args, **kwargs):
            loop = asyncio.get_event_loop()
            try:
                loop.run_until_complete(func(*args, **kwargs))
            finally:
                loop.close()
        return sync_wrapper
    return func
async.py 文件源码 项目:trafaret 作者: Deepwalker 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def async_transform(self, value, context=None):
        if not inspect.iscoroutinefunction(self.fn):
            return self.transform(value, context=context)
        if self.supports_context:
            res = await self.fn(value, context=context)
        else:
            res = await self.fn(value)
        if isinstance(res, DataError):
            raise res
        else:
            return res
run.py 文件源码 项目:cozmo-python-sdk 作者: anki 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def connect(f, conn_factory=conn.CozmoConnection, connector=None):
    '''Connects to the Cozmo Engine on the mobile device and supplies the connection to a function.

    Accepts a function, f, that is given a :class:`cozmo.conn.CozmoConnection` object as
    a parameter.

    The supplied function may be either an asynchronous coroutine function
    (normally defined using ``async def``) or a regular synchronous function.

    If an asynchronous function is supplied it will be run on the same thread
    as the Cozmo event loop and must use the ``await`` keyword to yield control
    back to the loop.

    If a synchronous function is supplied then it will run on the main thread
    and Cozmo's event loop will run on a separate thread.  Calls to
    asynchronous methods returned from CozmoConnection will automatically
    be translated to synchronous ones.

    The connect function will return once the supplied function has completed,
    as which time it will terminate the connection to the robot.

    Args:
        f (callable): The function to execute
        conn_factory (callable): Override the factory function to generate a
            :class:`cozmo.conn.CozmoConnection` (or subclass) instance.
        connector (:class:`DeviceConnector`): Optional instance of a DeviceConnector
            subclass that handles opening the USB connection to a device.
            By default it will connect to the first Android or iOS device that
            has the Cozmo app running in SDK mode.
    '''
    if asyncio.iscoroutinefunction(f):
        return _connect_async(f, conn_factory, connector)
    return _connect_sync(f, conn_factory, connector)
run.py 文件源码 项目:cozmo-python-sdk 作者: anki 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _connect_viewer(f, conn_factory, connector, viewer):
    # Run the viewer in the main thread, with the SDK running on a new background thread.
    loop = asyncio.new_event_loop()
    abort_future = concurrent.futures.Future()

    async def view_connector(coz_conn):
        try:
            await viewer.connect(coz_conn)

            if inspect.iscoroutinefunction(f):
                await f(coz_conn)
            else:
                await coz_conn._loop.run_in_executor(None, f, base._SyncProxy(coz_conn))
        finally:
            viewer.disconnect()

    try:
        if not inspect.iscoroutinefunction(f):
            conn_factory = functools.partial(conn_factory, _sync_abort_future=abort_future)
        lt = _LoopThread(loop, f=view_connector, conn_factory=conn_factory, connector=connector)
        lt.start()
        viewer.mainloop()
    except BaseException as e:
        abort_future.set_exception(exceptions.SDKShutdown(repr(e)))
        raise
    finally:
        lt.stop()


问题


面经


文章

微信
公众号

扫码关注公众号