Python inspect.isgeneratorfunction() Examples

The following are 30 code examples of inspect.isgeneratorfunction(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module inspect , or try the search function .
Example #1
Source File: threading.py    From napari with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
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 
Example #2
Source File: test_inspect.py    From BinderFilter with MIT License 6 votes vote down vote up
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)) 
Example #3
Source File: __init__.py    From mailur with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #4
Source File: test_inspect.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: base.py    From dffml with MIT License 6 votes vote down vote up
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 
Example #6
Source File: test_inspect.py    From oss-ftp with MIT License 6 votes vote down vote up
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)) 
Example #7
Source File: response.py    From python-ddd with MIT License 6 votes vote down vote up
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 
Example #8
Source File: common_pytest.py    From python-pytest-cases with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #9
Source File: test_inspect.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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)) 
Example #10
Source File: pretty.py    From Jacinle with MIT License 5 votes vote down vote up
def default(self, obj):
        if hasattr(obj, '__jsonify__'):
            json_object = obj.__jsonify__()
            if isinstance(json_object, six.string_types):
                return json_object
            return self.encode(json_object)
        else:
            raise TypeError("Object of type '%s' is not JSON serializable." % obj.__class__.__name__)

        if 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 
Example #11
Source File: __init__.py    From python-aspectlib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, advising_function, bind=False):
        if not isgeneratorfunction(advising_function):
            raise ExpectedGeneratorFunction("advising_function %s must be a generator function." % advising_function)
        self.advising_function = advising_function
        self.bind = bind 
Example #12
Source File: usb1.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _validContext(func):
        # Defined inside USBContext so we can access "self.__*".
        @contextlib.contextmanager
        def refcount(self):
            with self.__context_cond:
                if not self.__context_p and self.__auto_open:
                    # BBB
                    warnings.warn(
                        'Use "with USBContext() as context:" for safer cleanup'
                        ' on interpreter shutdown. See also USBContext.open().',
                        DeprecationWarning,
                    )
                    self.open()
                self.__context_refcount += 1
            try:
                yield
            finally:
                with self.__context_cond:
                    self.__context_refcount -= 1
                    if not self.__context_refcount:
                        self.__context_cond.notifyAll()
        if inspect.isgeneratorfunction(func):
            def wrapper(self, *args, **kw):
                with refcount(self):
                    if self.__context_p:
                        # pylint: disable=not-callable
                        for value in func(self, *args, **kw):
                            # pylint: enable=not-callable
                            yield value
        else:
            def wrapper(self, *args, **kw):
                with refcount(self):
                    if self.__context_p:
                        # pylint: disable=not-callable
                        return func(self, *args, **kw)
                        # pylint: enable=not-callable
        functools.update_wrapper(wrapper, func)
        return wrapper
    # pylint: enable=no-self-argument,protected-access 
Example #13
Source File: peewee_validates.py    From peewee-validates with MIT License 5 votes vote down vote up
def isiterable_notstring(value):
    """
    Returns True if the value is iterable but not a string. Otherwise returns False.

    :param value: Value to check.
    """
    if isinstance(value, str):
        return False
    return isinstance(value, Iterable) or isgeneratorfunction(value) or isgenerator(value) 
Example #14
Source File: tracer2.py    From executing with MIT License 5 votes vote down vote up
def __call__(self, function):
        if iscoroutinefunction(function):
            raise NotImplementedError("coroutines are not supported, sorry!")

        self.target_codes.add(function.__code__)

        @functools.wraps(function)
        def simple_wrapper(*args, **kwargs):
            with self:
                return function(*args, **kwargs)

        @functools.wraps(function)
        def generator_wrapper(*args, **kwargs):
            gen = function(*args, **kwargs)
            method, incoming = gen.send, None
            while True:
                with self:
                    try:
                        outgoing = method(incoming)
                    except StopIteration:
                        return
                try:
                    method, incoming = gen.send, (yield outgoing)
                except Exception as e:
                    method, incoming = gen.throw, e

        if inspect.isgeneratorfunction(function):
            return generator_wrapper
        else:
            return simple_wrapper 
Example #15
Source File: termui.py    From rules_pip with MIT License 5 votes vote down vote up
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) 
Example #16
Source File: utils.py    From simple-model with MIT License 5 votes vote down vote up
def is_not_special_object(obj):
    return not any((
        inspect.isclass(obj),
        inspect.ismethod(obj),
        inspect.isfunction(obj),
        inspect.isgeneratorfunction(obj),
        inspect.isgenerator(obj),
        inspect.isroutine(obj),
        isinstance(obj, property),
    )) 
Example #17
Source File: wsgi.py    From masakari with Apache License 2.0 5 votes vote down vote up
def pre_process_extensions(self, extensions, request, action_args):
        # List of callables for post-processing extensions
        post = []

        for ext in extensions:
            if inspect.isgeneratorfunction(ext):
                response = None

                # If it's a generator function, the part before the
                # yield is the preprocessing stage
                try:
                    with ResourceExceptionHandler():
                        gen = ext(req=request, **action_args)
                        response = next(gen)
                except Fault as ex:
                    response = ex

                # We had a response...
                if response:
                    return response, []

                # No response, queue up generator for post-processing
                post.append(gen)
            else:
                # Regular functions only perform post-processing
                post.append(ext)

        # None is response, it means we keep going. We reverse the
        # extension list for post-processing.
        return None, reversed(post) 
Example #18
Source File: hookregistry.py    From radish with MIT License 5 votes vote down vote up
def register(
        self, what, when, func, on_tags, order, is_formatter=False, always=False
    ):
        """Register the given Hook for later execution"""
        if inspect.isgeneratorfunction(func):
            # the registered function is a generator hook
            hook_impl = GeneratorHookImpl(
                what, func, on_tags, order, is_formatter, always
            )

            if (
                hook_impl in self._hooks["before"][what]
                and hook_impl in self._hooks["after"][what]
            ):
                # NOTE: allow a Hook Implementation to be registered multiple times.
                #       This can happend when one hook module imports another in the same
                #       RADISH_BASEDIR.
                return

            # insert the HookImpl in the order given by ``order``.
            bisect.insort_right(self._hooks["before"][what], hook_impl)
            bisect.insort_right(self._hooks["after"][what], hook_impl)
        else:
            # we have regular hook
            hook_impl = HookImpl(what, when, func, on_tags, order, is_formatter, always)

            if hook_impl in self._hooks[when][what]:
                # NOTE: allow a Hook Implementation to be registered multiple times.
                #       This can happend when one hook module imports another in the same
                #       RADISH_BASEDIR.
                return

            # insert the HookImpl in the order given by ``order``.
            bisect.insort_right(self._hooks[when][what], hook_impl) 
Example #19
Source File: __init__.py    From ambassador with Apache License 2.0 5 votes vote down vote up
def multi(dispatch_fn):
    gen = inspect.isgeneratorfunction(dispatch_fn)

    if gen:
        def multifun(*args, **kwargs):
            for key in dispatch_fn(*args, **kwargs):
                try:
                    action = multifun.__multi__[key]
                    break
                except KeyError:
                    continue
            else:
                action = multifun.__multi_default__
            return action(*args, **kwargs)
    else:
        def multifun(*args, **kwargs):
            key = dispatch_fn(*args, **kwargs)
            action = multifun.__multi__.get(key, multifun.__multi_default__)
            return action(*args, **kwargs)

    multifun.when = lambda *keys: _when(multifun, keys)
    multifun.default = _default(multifun)
    multifun.__multi__ = {}
    # Default default
    multifun.__multi_default__ = lambda *args, **kwargs: _error(multifun,
                                                                dispatch_fn(*args, **kwargs) if gen
                                                                else [dispatch_fn(*args, **kwargs)],
                                                                args,
                                                                kwargs)

    functools.update_wrapper(multifun, dispatch_fn)
    return multifun 
Example #20
Source File: _asynctest.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _run(self, methodName, result):
        from twisted.internet import reactor
        timeout = self.getTimeout()
        def onTimeout(d):
            e = defer.TimeoutError("%r (%s) still running at %s secs"
                % (self, methodName, timeout))
            f = failure.Failure(e)
            # try to errback the deferred that the test returns (for no gorram
            # reason) (see issue1005 and test_errorPropagation in
            # test_deferred)
            try:
                d.errback(f)
            except defer.AlreadyCalledError:
                # if the deferred has been called already but the *back chain
                # is still unfinished, crash the reactor and report timeout
                # error ourself.
                reactor.crash()
                self._timedOut = True # see self._wait
                todo = self.getTodo()
                if todo is not None and todo.expected(f):
                    result.addExpectedFailure(self, f, todo)
                else:
                    result.addError(self, f)
        onTimeout = utils.suppressWarnings(
            onTimeout, util.suppress(category=DeprecationWarning))
        method = getattr(self, methodName)
        if inspect.isgeneratorfunction(method):
            exc = TypeError(
                '%r is a generator function and therefore will never run' % (
                    method,))
            return defer.fail(exc)
        d = defer.maybeDeferred(
            utils.runWithWarningsSuppressed, self._getSuppress(), method)
        call = reactor.callLater(timeout, onTimeout, d)
        d.addBoth(lambda x : call.active() and call.cancel() or x)
        return d 
Example #21
Source File: py35support.py    From python-aspectlib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def decorate_advising_generator_py35(advising_function, cutpoint_function, bind):
    assert isgeneratorfunction(cutpoint_function)

    def advising_generator_wrapper_py35(*args, **kwargs):
        if bind:
            advisor = advising_function(cutpoint_function, *args, **kwargs)
        else:
            advisor = advising_function(*args, **kwargs)
        if not isgenerator(advisor):
            raise ExpectedGenerator("advising_function %s did not return a generator." % advising_function)
        try:
            advice = next(advisor)
            while True:
                logdebug('Got advice %r from %s', advice, advising_function)
                if advice is Proceed or advice is None or isinstance(advice, Proceed):
                    if isinstance(advice, Proceed):
                        args = advice.args
                        kwargs = advice.kwargs
                    gen = cutpoint_function(*args, **kwargs)
                    try:
                        result = yield from gen
                    except BaseException:
                        advice = advisor.throw(*sys.exc_info())
                    else:
                        try:
                            advice = advisor.send(result)
                        except StopIteration:
                            return result
                    finally:
                        gen.close()
                elif advice is Return:
                    return
                elif isinstance(advice, Return):
                    return advice.value
                else:
                    raise UnacceptableAdvice("Unknown advice %s" % advice)
        finally:
            advisor.close()
    return mimic(advising_generator_wrapper_py35, cutpoint_function) 
Example #22
Source File: termui.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
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) 
Example #23
Source File: termui.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
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) 
Example #24
Source File: key_bindings.py    From napari with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def press_key(self, key_combo):
        """Simulate a key press to activate a keybinding.

        Parameters
        ----------
        key_combo : str
            Key combination.
        """
        key_combo = normalize_key_combo(key_combo)
        keymap = self.active_keymap
        if key_combo in keymap:
            func = keymap[key_combo]
        elif Ellipsis in keymap:  # catch-all
            func = keymap[...]
        else:
            return  # no keybinding found

        if func is Ellipsis:  # blocker
            return
        elif not callable(func):
            raise TypeError(f"expected {func} to be callable")

        gen = func()

        if inspect.isgeneratorfunction(func):
            try:
                next(gen)  # call function
            except StopIteration:  # only one statement
                pass
            else:
                key, _ = parse_key_combo(key_combo)
                self._key_release_generators[key] = gen 
Example #25
Source File: threading.py    From napari with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, func: Callable, *args, **kwargs):
        if inspect.isgeneratorfunction(func):
            raise TypeError(
                f"Generator function {func} cannot be used with "
                "FunctionWorker, use GeneratorWorker instead"
            )
        super().__init__()

        self._func = func
        self._args = args
        self._kwargs = kwargs 
Example #26
Source File: test_threading.py    From napari with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_as_generator_function():
    """Test we can convert a regular function to a generator function."""

    def func():
        return

    assert not inspect.isgeneratorfunction(func)

    newfunc = threading.as_generator_function(func)
    assert inspect.isgeneratorfunction(newfunc)
    assert list(newfunc()) == [None]


# qtbot is necessary for qthreading here.
# note: pytest-cov cannot check coverage of code run in the other thread. 
Example #27
Source File: messaging.py    From CEX.IO-Client-Python3.5 with MIT License 5 votes vote down vote up
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 
Example #28
Source File: test_inspect.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_excluding_predicates(self):
        global tb
        self.istest(inspect.isbuiltin, 'sys.exit')
        self.istest(inspect.isbuiltin, '[].append')
        self.istest(inspect.iscode, 'mod.spam.__code__')
        try:
            1/0
        except:
            tb = sys.exc_info()[2]
            self.istest(inspect.isframe, 'tb.tb_frame')
            self.istest(inspect.istraceback, 'tb')
            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))
        finally:
            # Clear traceback and all the frames and local variables hanging to it.
            tb = None
        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.isdatadescriptor, 'collections.defaultdict.default_factory')
        self.istest(inspect.isgenerator, '(x for x in range(2))')
        self.istest(inspect.isgeneratorfunction, 'generator_function_example')

        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            self.istest(inspect.iscoroutine, 'coroutine_function_example(1)')
            self.istest(inspect.iscoroutinefunction, 'coroutine_function_example')

        if hasattr(types, 'MemberDescriptorType'):
            self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
        else:
            self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days)) 
Example #29
Source File: test_inspect.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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 or \
               predicate == inspect.iscoroutinefunction) and \
               other == inspect.isfunction:
                continue
            self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp)) 
Example #30
Source File: test_plugin_hooks.py    From CloudBot with GNU General Public License v3.0 5 votes vote down vote up
def test_coroutine_hooks(hook):
    if inspect.isgeneratorfunction(hook.function):  # pragma: no cover
        assert asyncio.iscoroutinefunction(hook.function), \
            "Non-coroutine generator function used for a hook. This is most liekly due to incorrect ordering of the " \
            "hook/coroutine decorators."