python类isgeneratorfunction()的实例源码

agent.py 文件源码 项目:osbrain 作者: opensistemas-hub 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def _process_rep_event(self, socket, addr, data):
        """
        Process a REP socket's event.

        Parameters
        ----------
        socket : zmq.Socket
            Socket that generated the event.
        addr : AgentAddress
            AgentAddress associated with the socket that generated the event.
        data : bytes
            Data received on the socket.
        """
        message = deserialize_message(message=data, serializer=addr.serializer)
        handler = self.handler[socket]
        if inspect.isgeneratorfunction(handler):
            generator = handler(self, message)
            socket.send(serialize_message(next(generator), addr.serializer))
            execute_code_after_yield(generator)
        else:
            reply = handler(self, message)
            socket.send(serialize_message(reply, addr.serializer))
async.py 文件源码 项目:poloniex-api 作者: absortium 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def trollbox_wrapper(handler):
    async def decorator(data):
        if len(data) != 5:
            return

        type_ = data[0]
        message_id = data[1]
        username = data[2]
        text = data[3]
        reputation = data[4]

        kwargs = {
            "id": message_id,
            "username": username,
            "type": type_,
            "text": text,
            "reputation": reputation
        }

        if inspect.isgeneratorfunction(handler):
            await handler(**kwargs)
        else:
            handler(**kwargs)

    return decorator
bench.py 文件源码 项目:deb-python-falcon 作者: openstack 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def create_bench(name, env):
    srmock = helpers.StartResponseMock()

    function = name.lower().replace('-', '_')
    app = eval('create.{0}(BODY, HEADERS)'.format(function))

    def bench():
        app(env, srmock)
        if srmock.status != '200 OK':
            raise AssertionError(srmock.status + ' != 200 OK')

    def bench_generator():
        exhaust(app(env, srmock))
        if srmock.status != '200 OK':
            raise AssertionError(srmock.status + ' != 200 OK')

    if inspect.isgeneratorfunction(app):
        return bench_generator
    else:
        return bench
resource.py 文件源码 项目:SimPype 作者: Mallets 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def __service(func, resource, message):
    assert isinstance(resource, Resource)
    assert isinstance(message, simpype.Message)
    message.location = resource
    if inspect.isgeneratorfunction(func):
        mid = str(message.id)+str(message.seq_num)
        a_serve = resource.env.process(func(resource, message))
        resource.task[mid] = Task(message.sim, message, a_serve)
        try:
            yield a_serve
            message.timestamp('resource.serve')
        except simpy.Interrupt as interrupt:
            message.timestamp('resource.'+str(interrupt.cause))
        del resource.task[mid]
    else:
        func(resource, message)
        message.timestamp('resource.serve')
    if message.next:
        resource.send(message)
    else:
        message.done()
custom_json.py 文件源码 项目:easy-py-web-app 作者: ma-ha 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def default(self, obj):
        if hasattr(obj, "to_json"):
            return self.default(obj.to_json())
        elif hasattr(obj, "__dict__"):
            d = dict(
                (key, value)
                for key, value in inspect.getmembers(obj)
                if not key.startswith("__")
                and not inspect.isabstract(value)
                and not inspect.isbuiltin(value)
                and not inspect.isfunction(value)
                and not inspect.isgenerator(value)
                and not inspect.isgeneratorfunction(value)
                and not inspect.ismethod(value)
                and not inspect.ismethoddescriptor(value)
                and not inspect.isroutine(value)
            )
            return self.default(d)
        return obj
test_inspect.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_excluding_predicates(self):
        self.istest(inspect.isbuiltin, 'sys.exit')
        if check_impl_detail():
            self.istest(inspect.isbuiltin, '[].append')
        self.istest(inspect.iscode, 'mod.spam.__code__')
        self.istest(inspect.isframe, 'tb.tb_frame')
        self.istest(inspect.isfunction, 'mod.spam')
        self.istest(inspect.isfunction, 'mod.StupidGit.abuse')
        self.istest(inspect.ismethod, 'git.argue')
        self.istest(inspect.ismodule, 'mod')
        self.istest(inspect.istraceback, 'tb')
        self.istest(inspect.isdatadescriptor, 'collections.defaultdict.default_factory')
        self.istest(inspect.isgenerator, '(x for x in range(2))')
        self.istest(inspect.isgeneratorfunction, 'generator_function_example')
        if hasattr(types, 'GetSetDescriptorType'):
            self.istest(inspect.isgetsetdescriptor,
                        'type(tb.tb_frame).f_locals')
        else:
            self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
        if hasattr(types, 'MemberDescriptorType'):
            self.istest(inspect.ismemberdescriptor,
                        'type(lambda: None).__globals__')
        else:
            self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
client.py 文件源码 项目:python-etcd3 作者: kragniz 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _handle_errors(f):
    if inspect.isgeneratorfunction(f):
        def handler(*args, **kwargs):
            try:
                for data in f(*args, **kwargs):
                    yield data
            except grpc.RpcError as exc:
                _translate_exception(exc)
    else:
        def handler(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except grpc.RpcError as exc:
                _translate_exception(exc)

    return functools.wraps(f)(handler)
test_inspect.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def test_excluding_predicates(self):
        self.istest(inspect.isbuiltin, 'sys.exit')
        self.istest(inspect.isbuiltin, '[].append')
        self.istest(inspect.iscode, 'mod.spam.func_code')
        self.istest(inspect.isframe, 'tb.tb_frame')
        self.istest(inspect.isfunction, 'mod.spam')
        self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
        self.istest(inspect.ismethod, 'git.argue')
        self.istest(inspect.ismodule, 'mod')
        self.istest(inspect.istraceback, 'tb')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
        self.istest(inspect.isgenerator, '(x for x in xrange(2))')
        self.istest(inspect.isgeneratorfunction, 'generator_function_example')
        if hasattr(types, 'GetSetDescriptorType'):
            self.istest(inspect.isgetsetdescriptor,
                        'type(tb.tb_frame).f_locals')
        else:
            self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
        if hasattr(types, 'MemberDescriptorType'):
            self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
        else:
            self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
test_inspect.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_excluding_predicates(self):
        self.istest(inspect.isbuiltin, 'sys.exit')
        self.istest(inspect.isbuiltin, '[].append')
        self.istest(inspect.iscode, 'mod.spam.func_code')
        self.istest(inspect.isframe, 'tb.tb_frame')
        self.istest(inspect.isfunction, 'mod.spam')
        self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
        self.istest(inspect.ismethod, 'git.argue')
        self.istest(inspect.ismodule, 'mod')
        self.istest(inspect.istraceback, 'tb')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
        self.istest(inspect.isgenerator, '(x for x in xrange(2))')
        self.istest(inspect.isgeneratorfunction, 'generator_function_example')
        if hasattr(types, 'GetSetDescriptorType'):
            self.istest(inspect.isgetsetdescriptor,
                        'type(tb.tb_frame).f_locals')
        else:
            self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
        if hasattr(types, 'MemberDescriptorType'):
            self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
        else:
            self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
core.py 文件源码 项目:python-fire 作者: google 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _PrintResult(component_trace, verbose=False):
  """Prints the result of the Fire call to stdout in a human readable way."""
  # TODO: Design human readable deserializable serialization method
  # and move serialization to it's own module.
  result = component_trace.GetResult()

  if isinstance(result, (list, set, types.GeneratorType)):
    for i in result:
      print(_OneLineResult(i))
  elif inspect.isgeneratorfunction(result):
    raise NotImplementedError
  elif isinstance(result, dict):
    print(_DictAsString(result, verbose))
  elif isinstance(result, tuple):
    print(_OneLineResult(result))
  elif isinstance(result,
                  (bool, six.string_types, six.integer_types, float, complex)):
    print(result)
  elif result is not None:
    print(helputils.HelpString(result, component_trace, verbose))
fixture.py 文件源码 项目:reahl 作者: reahl 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def __getattr__(self, name):
        if name.startswith(self.factory_method_prefix):
            raise AttributeError(name)

        factory = self.get_factory_method_for(name)
        if inspect.isgeneratorfunction(factory):
            with self.wrapped_attribute_error():
                generator = factory()
                instance = next(generator)
            self.attribute_generators.append(generator)
        else:
            with self.wrapped_attribute_error():
                instance = factory()

        setattr(self, name, instance)
        self.attributes_set[name] = instance
        return instance
test_inspect.py 文件源码 项目:pefile.pypy 作者: cloudtracer 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def test_excluding_predicates(self):
        self.istest(inspect.isbuiltin, 'sys.exit')
        if check_impl_detail():
            self.istest(inspect.isbuiltin, '[].append')
        self.istest(inspect.iscode, 'mod.spam.func_code')
        self.istest(inspect.isframe, 'tb.tb_frame')
        self.istest(inspect.isfunction, 'mod.spam')
        self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
        self.istest(inspect.ismethod, 'git.argue')
        self.istest(inspect.ismodule, 'mod')
        self.istest(inspect.istraceback, 'tb')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
        self.istest(inspect.isgenerator, '(x for x in xrange(2))')
        self.istest(inspect.isgeneratorfunction, 'generator_function_example')
        if hasattr(types, 'GetSetDescriptorType'):
            self.istest(inspect.isgetsetdescriptor,
                        'type(tb.tb_frame).f_locals')
        else:
            self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
        if hasattr(types, 'MemberDescriptorType'):
            self.istest(inspect.ismemberdescriptor, 'type(lambda: None).func_globals')
        else:
            self.assertFalse(inspect.ismemberdescriptor(type(lambda: None).func_globals))
test_inspect.py 文件源码 项目:ndk-python 作者: gittor 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_excluding_predicates(self):
        self.istest(inspect.isbuiltin, 'sys.exit')
        self.istest(inspect.isbuiltin, '[].append')
        self.istest(inspect.iscode, 'mod.spam.func_code')
        self.istest(inspect.isframe, 'tb.tb_frame')
        self.istest(inspect.isfunction, 'mod.spam')
        self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
        self.istest(inspect.ismethod, 'git.argue')
        self.istest(inspect.ismodule, 'mod')
        self.istest(inspect.istraceback, 'tb')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
        self.istest(inspect.isgenerator, '(x for x in xrange(2))')
        self.istest(inspect.isgeneratorfunction, 'generator_function_example')
        if hasattr(types, 'GetSetDescriptorType'):
            self.istest(inspect.isgetsetdescriptor,
                        'type(tb.tb_frame).f_locals')
        else:
            self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
        if hasattr(types, 'MemberDescriptorType'):
            self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
        else:
            self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
PhenoPacket.py 文件源码 项目:ga4gh-biosamples 作者: EBISPOT 项目源码 文件源码 阅读 52 收藏 0 点赞 0 评论 0
def default(self, obj):
        # if hasattr(obj, "to_json"):
        #     return self.default(obj.to_json())
        if isinstance(obj, Enum):
            return obj.name
        elif hasattr(obj, "__dict__"):
            d = dict(
                (key, value)
                for key, value in inspect.getmembers(obj)
                if not key.startswith("__")
                and not inspect.isabstract(value)
                and not inspect.isbuiltin(value)
                and not inspect.isfunction(value)
                and not inspect.isgenerator(value)
                and not inspect.isgeneratorfunction(value)
                and not inspect.ismethod(value)
                and not inspect.ismethoddescriptor(value)
                and not inspect.isroutine(value)
                and not self.isempty(value)
                and not value is None
            )
            return self.default(d)
        return obj
ohneio.py 文件源码 项目:ohneio 作者: acatton 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def protocol(func: typing.Callable[..., ProtocolGenerator[R]]) -> typing.Callable[..., Consumer[R]]:
    """Wraps a Ohne I/O protocol function.

    Under the hood this wraps the generator inside a :class:`~ohneio.Consumer`.

    Args:
        func (callable): Protocol function to wrap. (Protocol functions have to be generators)

    Returns:
        callable: wrapped function.
    """
    if not callable(func):  # pragma: no cover
        # This is for users misusing the library, type hinting already checks this
        raise ValueError("A protocol needs to a be a callable")
    if not inspect.isgeneratorfunction(func):  # pragma: no cover
        # This is for users misusing the library, type hinting already checks this
        raise ValueError("A protocol needs to be a generator function")

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return Consumer(func(*args, **kwargs))

    return wrapper
_testbase.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def tcp_client(client_prog,
               family=socket.AF_INET,
               timeout=10):

    if not inspect.isgeneratorfunction(client_prog):
        raise TypeError('client_prog: a generator function was expected')

    sock = socket.socket(family, socket.SOCK_STREAM)

    if timeout is None:
        raise RuntimeError('timeout is required')
    if timeout <= 0:
        raise RuntimeError('only blocking sockets are supported')
    sock.settimeout(timeout)

    srv = Client(sock, client_prog, timeout)
    return srv
bench.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 43 收藏 0 点赞 0 评论 0
def create_bench(name, env):
    srmock = helpers.StartResponseMock()

    function = name.lower().replace('-', '_')
    app = eval('create.{0}(BODY, HEADERS)'.format(function))

    def bench():
        app(env, srmock)
        if srmock.status != '200 OK':
            raise AssertionError(srmock.status + ' != 200 OK')

    def bench_generator():
        exhaust(app(env, srmock))
        if srmock.status != '200 OK':
            raise AssertionError(srmock.status + ' != 200 OK')

    if inspect.isgeneratorfunction(app):
        return bench_generator
    else:
        return bench
web_core.py 文件源码 项目:burnell-web 作者: BurnellLiu 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def add_route(app, fn):
    """
    ???????????WEB APP???
    :param app: WEB APP??
    :param fn: ????
    """
    # ?????????????
    method = getattr(fn, '__method__', None)
    path = getattr(fn, '__route__', None)
    if path is None or method is None:
        return

    # ????????????
    if not asyncio.iscoroutinefunction(fn) and not inspect.isgeneratorfunction(fn):
        fn = asyncio.coroutine(fn)

    logging.info('add route function: %s(%s), method(%s), path(%s)' %
                 (fn.__name__, ', '.join(inspect.signature(fn).parameters.keys()), method, path, ))

    app.router.add_route(method, path, fn)
contexts.py 文件源码 项目:easypy 作者: weka-io 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def __call__(self, func):
        if isgeneratorfunction(func):
            def inner(*args, **kwds):
                with self._recreate_cm():
                    yield from func(*args, **kwds)
        elif is_contextmanager(func):
            @contextmanager
            def inner(*args, **kwds):
                with self._recreate_cm():
                    with func(*args, **kwds) as ret:
                        yield ret
        else:
            def inner(*args, **kwds):
                with self._recreate_cm():
                    return func(*args, **kwds)
        return wraps(func)(inner)


# Some python version have a different signature for '_GeneratorContextManager.__init__', so we must adapt:
coroutines.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def _format_coroutine(coro):
    assert iscoroutine(coro)
    coro_name = getattr(coro, '__qualname__', coro.__name__)

    filename = coro.gi_code.co_filename
    if (isinstance(coro, CoroWrapper)
    and not inspect.isgeneratorfunction(coro.func)):
        filename, lineno = events._get_function_source(coro.func)
        if coro.gi_frame is None:
            coro_repr = '%s() done, defined at %s:%s' % (coro_name, filename, lineno)
        else:
            coro_repr = '%s() running, defined at %s:%s' % (coro_name, filename, lineno)
    elif coro.gi_frame is not None:
        lineno = coro.gi_frame.f_lineno
        coro_repr = '%s() running at %s:%s' % (coro_name, filename, lineno)
    else:
        lineno = coro.gi_code.co_firstlineno
        coro_repr = '%s() done, defined at %s:%s' % (coro_name, filename, lineno)

    return coro_repr
coroweb.py 文件源码 项目:awesome-webapp 作者: TsangTen 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def add_route(app, fn):
    '''
    ??????URL????
    '''
    method = getattr(fn, '__method__', None)
    path = getattr(fn, '__route__', None)
    if path is None or method is None:
        raise ValueError('@get or @post not defined in %s.' % str(fn))
    if not asyncio.iscoroutinefunction(fn) and not inspect.isgeneratorfunction(fn):
        fn = asyncio.coroutine(fn)
    logging.info('add route %s %s => %s(%s)' % (method, path, fn.__name__, ', '.join(inspect.signature(fn).parameters.keys())))
    app.router.add_route(method, path, RequestHandler(app, fn))


# ???????
# ???handler???????????????
discord_transport.py 文件源码 项目:plumeria 作者: sk89q 项目源码 文件源码 阅读 37 收藏 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)
providers.py 文件源码 项目:hypr2 作者: project-hypr 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def _call_meth(self, match_info, name):
        # call meth with variable segments of the request as arguments.
        meth = getattr(self, name)
        if (not asyncio.iscoroutinefunction(meth) and
                not inspect.isgeneratorfunction(meth)):
            meth = asyncio.coroutine(meth)

        # get variable segments for the current provider.
        var = {k: v for k, v in match_info.items() if not k.startswith('_')}

        # get method signature and apply variable segments
        req, _, kw, _ = inspect.getargspec(getattr(meth, '__wrapped__', meth))
        if kw is None:
            rv = yield from meth(**{k: v for k, v in var.items() if k in req})
        else:
            rv = yield from meth(**var)  # any kerword arguments is accepted
        return rv
task.py 文件源码 项目:mTasks 作者: theodox 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def __init__(self, fn, callback=None):

        # this will except if <fn> is not a coroutine or generator function
        # that can yield
        assert inspect.isgeneratorfunction(fn) or hasattr(fn, "__call__")

        Task._next_id += 1
        self.id = Task._next_id
        self.fn = fn()
        self.state = None
        if callable(callback) and not inspect.getargspec(callback).args:
            def cb(_):
                callback()

            self.callback = cb
        else:
            self.callback = callback
socket_spine.py 文件源码 项目:kervi 作者: kervi 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def default(self, obj):
        if hasattr(obj, "to_json"):
            return self.default(obj.to_json())
        elif hasattr(obj, "__dict__"):
            data = dict(
                (key, value)
                for key, value in inspect.getmembers(obj)
                if not key.startswith("__")
                and not inspect.isabstract(value)
                and not inspect.isbuiltin(value)
                and not inspect.isfunction(value)
                and not inspect.isgenerator(value)
                and not inspect.isgeneratorfunction(value)
                and not inspect.ismethod(value)
                and not inspect.ismethoddescriptor(value)
                and not inspect.isroutine(value)
            )
            return self.default(data)
        return obj
storage.py 文件源码 项目:kervi 作者: kervi 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def default(self, obj):
        if hasattr(obj, "to_json"):
            return self.default(obj.to_json())
        elif hasattr(obj, "__dict__"):
            data = dict(
                (key, value)
                for key, value in inspect.getmembers(obj)
                if not key.startswith("__")
                and not inspect.isabstract(value)
                and not inspect.isbuiltin(value)
                and not inspect.isfunction(value)
                and not inspect.isgenerator(value)
                and not inspect.isgeneratorfunction(value)
                and not inspect.ismethod(value)
                and not inspect.ismethoddescriptor(value)
                and not inspect.isroutine(value)
            )
            return self.default(data)
        return obj
zmqbus.py 文件源码 项目:kervi 作者: kervi 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def default(self, obj):
        if hasattr(obj, "to_json"):
            return self.default(obj.to_json())
        elif hasattr(obj, "__dict__"):
            data = dict(
                (key, value)
                for key, value in inspect.getmembers(obj)
                if not key.startswith("__")
                and not inspect.isabstract(value)
                and not inspect.isbuiltin(value)
                and not inspect.isfunction(value)
                and not inspect.isgenerator(value)
                and not inspect.isgeneratorfunction(value)
                and not inspect.ismethod(value)
                and not inspect.ismethoddescriptor(value)
                and not inspect.isroutine(value)
            )
            return self.default(data)
        return obj
dispycos.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _run_request(self, request, where, cpu, gen, *args, **kwargs):
        """Internal use only.
        """
        if isinstance(gen, str):
            name = gen
        else:
            name = gen.func_name

        if name in self._xfer_funcs:
            code = None
        else:
            # if not inspect.isgeneratorfunction(gen):
            #     logger.warning('"%s" is not a valid generator function', name)
            #     raise StopIteration([])
            code = inspect.getsource(gen).lstrip()

        def _run_req(task=None):
            msg = {'req': 'job', 'auth': self._auth,
                   'job': _DispycosJob_(request, task, name, where, cpu, code, args, kwargs)}
            if (yield self.scheduler.deliver(msg, timeout=MsgTimeout)) == 1:
                reply = yield task.receive()
                if isinstance(reply, Task):
                    if self.status_task:
                        msg = DispycosTaskInfo(reply, args, kwargs, time.time())
                        self.status_task.send(DispycosStatus(Scheduler.TaskCreated, msg))
                if not request.endswith('async'):
                    reply = yield task.receive()
            else:
                reply = None
            raise StopIteration(reply)

        yield Task(_run_req).finish()
netpycos.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def __init__(self, method, name=None):
        """'method' must be generator method; this is used to create tasks. If
        'name' is not given, method's function name is used for registering.
        """
        if not inspect.isgeneratorfunction(method):
            raise RuntimeError('RTI method must be generator function')
        self._method = method
        if name:
            self._name = name
        else:
            self._name = method.__name__
        if not RTI._pycos:
            RTI._pycos = Pycos.instance()
        self._location = None
        self._mid = None


问题


面经


文章

微信
公众号

扫码关注公众号