当前位置: 首页>>代码示例>>Python>>正文


Python inspect.isgeneratorfunction方法代码示例

本文整理汇总了Python中inspect.isgeneratorfunction方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.isgeneratorfunction方法的具体用法?Python inspect.isgeneratorfunction怎么用?Python inspect.isgeneratorfunction使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在inspect的用法示例。


在下文中一共展示了inspect.isgeneratorfunction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_excluding_predicates

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
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)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:25,代码来源:test_inspect.py

示例2: pytest_fixture

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def pytest_fixture(hook=None, name=None, **kwargs):
        """Generator-aware pytest.fixture decorator for legacy pytest versions"""
        def _decorate(f):
            if name is not None:
                # 'name' argument is not supported in this old version, use the __name__ trick.
                f.__name__ = name

            # call hook if needed
            if hook is not None:
                f = hook(f)

            # create the fixture
            if isgeneratorfunction(f):
                return pytest.yield_fixture(**kwargs)(f)
            else:
                return pytest.fixture(**kwargs)(f)
        return _decorate 
开发者ID:smarie,项目名称:python-pytest-cases,代码行数:19,代码来源:common_pytest.py

示例3: test_iscoroutine

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def test_iscoroutine(self):
        gen_coro = gen_coroutine_function_example(1)
        coro = coroutine_function_example(1)

        self.assertFalse(
            inspect.iscoroutinefunction(gen_coroutine_function_example))
        self.assertFalse(inspect.iscoroutine(gen_coro))

        self.assertTrue(
            inspect.isgeneratorfunction(gen_coroutine_function_example))
        self.assertTrue(inspect.isgenerator(gen_coro))

        self.assertTrue(
            inspect.iscoroutinefunction(coroutine_function_example))
        self.assertTrue(inspect.iscoroutine(coro))

        self.assertFalse(
            inspect.isgeneratorfunction(coroutine_function_example))
        self.assertFalse(inspect.isgenerator(coro))

        coro.close(); gen_coro.close() # silence warnings 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:23,代码来源:test_inspect.py

示例4: __init__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def __init__(
        self,
        func: Callable,
        *args,
        SignalsClass: Type[QObject] = GeneratorWorkerSignals,
        **kwargs,
    ):
        if not inspect.isgeneratorfunction(func):
            raise TypeError(
                f"Regular function {func} cannot be used with "
                "GeneratorWorker, use FunctionWorker instead"
            )
        super().__init__(SignalsClass=SignalsClass)

        self._gen = func(*args, **kwargs)
        self._incoming_value = None
        self._pause_requested = False
        self._resume_requested = False
        self._paused = False
        # polling interval: ONLY relevant if the user paused a running worker
        self._pause_interval = 0.01 
开发者ID:napari,项目名称:napari,代码行数:23,代码来源:threading.py

示例5: _imp

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def _imp(cls, loaded):
        """
        Returns the operation implemention from a loaded entrypoint object, or
        None if its not an operation implemention or doesn't have the imp
        parameter which is an operation implemention.
        """
        for obj in [getattr(loaded, "imp", None), loaded]:
            if inspect.isclass(obj) and issubclass(obj, cls):
                return obj
        if (
            inspect.isfunction(loaded)
            or inspect.isgeneratorfunction(loaded)
            or inspect.iscoroutinefunction(loaded)
            or inspect.isasyncgenfunction(loaded)
        ):
            return op(loaded).imp
        return None 
开发者ID:intel,项目名称:dffml,代码行数:19,代码来源:base.py

示例6: fn_time

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def fn_time(func, desc=None):
    @contextmanager
    def timing(*a, **kw):
        start = time.time()
        try:
            yield
        finally:
            d = desc if desc else fn_desc(func, *a, **kw)
            log.debug('%s: done for %.2fs', d, time.time() - start)

    def inner_fn(*a, **kw):
        with timing(*a, **kw):
            return func(*a, **kw)

    def inner_gen(*a, **kw):
        with timing(*a, **kw):
            yield from func(*a, **kw)

    inner = inner_gen if inspect.isgeneratorfunction(func) else inner_fn
    return ft.wraps(func)(inner) 
开发者ID:naspeh,项目名称:mailur,代码行数:22,代码来源:__init__.py

示例7: default

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat() + 'Z'
        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 
开发者ID:Ermlab,项目名称:python-ddd,代码行数:23,代码来源:response.py

示例8: isgeneratorfunction

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def isgeneratorfunction(caller):
        return False 
开发者ID:remg427,项目名称:misp42splunk,代码行数:4,代码来源:decorator.py

示例9: decorate

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def decorate(func, caller, extras=()):
    """
    decorate(func, caller) decorates a function using a caller.
    If the caller is a generator function, the resulting function
    will be a generator function.
    """
    evaldict = dict(_call_=caller, _func_=func)
    es = ''
    for i, extra in enumerate(extras):
        ex = '_e%d_' % i
        evaldict[ex] = extra
        es += ex + ', '

    if '3.5' <= sys.version < '3.6':
        # with Python 3.5 isgeneratorfunction returns True for all coroutines
        # however we know that it is NOT possible to have a generator
        # coroutine in python 3.5: PEP525 was not there yet
        generatorcaller = isgeneratorfunction(
            caller) and not iscoroutinefunction(caller)
    else:
        generatorcaller = isgeneratorfunction(caller)
    if generatorcaller:
        fun = FunctionMaker.create(
            func, "for res in _call_(_func_, %s%%(shortsignature)s):\n"
                  "    yield res" % es, evaldict, __wrapped__=func)
    else:
        fun = FunctionMaker.create(
            func, "return _call_(_func_, %s%%(shortsignature)s)" % es,
            evaldict, __wrapped__=func)
    if hasattr(func, '__qualname__'):
        fun.__qualname__ = func.__qualname__
    return fun 
开发者ID:remg427,项目名称:misp42splunk,代码行数:34,代码来源:decorator.py

示例10: test_functions_are_generators

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def test_functions_are_generators(func2test, method_param, base_class, expected):
    from inspect import isgenerator, isgeneratorfunction

    func_obj = _load_obj(func_name=func2test)
    generator_obj = func_obj(method_param, base_class)

    assert isgeneratorfunction(func_obj) is expected
    assert isgenerator(generator_obj) is expected 
开发者ID:nokia,项目名称:moler,代码行数:10,代码来源:test_cmds_events_doc.py

示例11: echo_via_pager

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def echo_via_pager(text_or_generator, color=None):
    """This function takes a text and shows it via an environment specific
    pager on stdout.

    .. versionchanged:: 3.0
       Added the `color` flag.

    :param text_or_generator: the text to page, or alternatively, a
                              generator emitting the text to page.
    :param color: controls if the pager supports ANSI colors or not.  The
                  default is autodetection.
    """
    color = resolve_color_default(color)

    if inspect.isgeneratorfunction(text_or_generator):
        i = text_or_generator()
    elif isinstance(text_or_generator, string_types):
        i = [text_or_generator]
    else:
        i = iter(text_or_generator)

    # convert every element of i to a text type if necessary
    text_generator = (el if isinstance(el, string_types) else text_type(el)
                      for el in i)

    from ._termui_impl import pager
    return pager(itertools.chain(text_generator, "\n"), color) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:29,代码来源:termui.py

示例12: read_session

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def read_session(function):
    '''
    decorator that set the session variable to use inside a function.
    With that decorator it's possible to use the session variable like if a global variable session is declared.

    session is a sqlalchemy session, and you can get one calling get_session().
    This is useful if only SELECTs and the like are being done; anything involving
    INSERTs, UPDATEs etc should use transactional_session.
    '''
    @retry(retry_on_exception=retry_if_db_connection_error,
           wait_fixed=500,
           stop_max_attempt_number=2,
           wrap_exception=False)
    @wraps(function)
    def new_funct(*args, **kwargs):
        if isgeneratorfunction(function):
            raise RucioException('read_session decorator should not be used with generator. Use stream_session instead.')

        if not kwargs.get('session'):
            session = get_session()
            try:
                kwargs['session'] = session
                return function(*args, **kwargs)
            except TimeoutError as error:
                session.rollback()  # pylint: disable=maybe-no-member
                raise DatabaseException(str(error))
            except DatabaseError as error:
                session.rollback()  # pylint: disable=maybe-no-member
                raise DatabaseException(str(error))
            except:
                session.rollback()  # pylint: disable=maybe-no-member
                raise
            finally:
                session.remove()
        try:
            return function(*args, **kwargs)
        except:
            raise
    new_funct.__doc__ = function.__doc__
    return new_funct 
开发者ID:rucio,项目名称:rucio,代码行数:42,代码来源:session.py

示例13: is_generator

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def is_generator(obj):
    import inspect

    return obj is not None and (inspect.isgeneratorfunction(obj) or inspect.isgenerator(obj) or hasattr(obj, 'next') or hasattr(obj, '__next__')) 
开发者ID:aetros,项目名称:aetros-cli,代码行数:6,代码来源:Trainer.py

示例14: is_generator

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def is_generator(func):
    genfunc = inspect.isgeneratorfunction(func)
    return genfunc and not iscoroutinefunction(func) 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:5,代码来源:compat.py

示例15: istest

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isgeneratorfunction [as 别名]
def istest(self, predicate, exp):
        obj = eval(exp)
        self.assertTrue(predicate(obj), '%s(%s)' % (predicate.__name__, exp))

        for other in self.predicates - set([predicate]):
            if predicate == inspect.isgeneratorfunction and\
               other == inspect.isfunction:
                continue
            self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:11,代码来源:test_inspect.py


注:本文中的inspect.isgeneratorfunction方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。