Python types.FrameType() Examples

The following are 30 code examples of types.FrameType(). 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 types , or try the search function .
Example #1
Source File: logging.py    From fastapi-realworld-example-app with MIT License 9 votes vote down vote up
def emit(self, record: logging.LogRecord) -> None:  # pragma: no cover
        # Get corresponding Loguru level if it exists
        try:
            level = logger.level(record.levelname).name
        except ValueError:
            level = str(record.levelno)

        # Find caller from where originated the logged message
        frame, depth = logging.currentframe(), 2
        while frame.f_code.co_filename == logging.__file__:  # noqa: WPS609
            frame = cast(FrameType, frame.f_back)
            depth += 1

        logger.opt(depth=depth, exception=record.exc_info).log(
            level, record.getMessage(),
        ) 
Example #2
Source File: record.py    From recipes-py with Apache License 2.0 7 votes vote down vote up
def _skip_frame_predicates(self):
    """A tuple of predicate functions to decide whether or not to skip a given
    frame for warning attribution. The predicates are connected with logic OR,
    meaning that if one of the predicates says to skip, the frame will be
    skipped. A predicate function will have signature as follows.

    Args:
      * name (str) - Fully qualified warning name e.g. 'repo/WARNING_NAME'
      * index (int) - The index of the provided frame in call stack. Outer
      frame has larger index.
      * frame (types.FrameType) - A frame in call stack that the predicate
      function is currently evaluating against

    Returns a human-readable reason (str) why the given frame should be skipped.
    Returns None if the warning can be attributed to the given frame.
    """
    return (
      # Skip the first frame as it is where the warning is being issued
      lambda name, index, frame: 'warning issued frame' if index == 0 else None,
      self._non_recipe_code_predicate,
      escape_warning_predicate
    ) 
Example #3
Source File: utils.py    From paasta with Apache License 2.0 7 votes vote down vote up
def timeout(
    seconds: int = 10,
    error_message: str = os.strerror(errno.ETIME),
    use_signals: bool = True,
) -> Callable[[Callable[..., _TimeoutFuncRetType]], Callable[..., _TimeoutFuncRetType]]:
    if use_signals:

        def decorate(
            func: Callable[..., _TimeoutFuncRetType]
        ) -> Callable[..., _TimeoutFuncRetType]:
            def _handle_timeout(signum: int, frame: FrameType) -> None:
                raise TimeoutError(error_message)

            def wrapper(*args: Any, **kwargs: Any) -> _TimeoutFuncRetType:
                signal.signal(signal.SIGALRM, _handle_timeout)
                signal.alarm(seconds)
                try:
                    result = func(*args, **kwargs)
                finally:
                    signal.alarm(0)
                return result

            return wraps(func)(wrapper)

    else:

        def decorate(
            func: Callable[..., _TimeoutFuncRetType]
        ) -> Callable[..., _TimeoutFuncRetType]:
            # https://github.com/python/mypy/issues/797
            return _Timeout(func, seconds, error_message)  # type: ignore

    return decorate 
Example #4
Source File: test_code.py    From pytest with MIT License 6 votes vote down vote up
def test_frame_getargs() -> None:
    def f1(x) -> FrameType:
        return sys._getframe(0)

    fr1 = Frame(f1("a"))
    assert fr1.getargs(var=True) == [("x", "a")]

    def f2(x, *y) -> FrameType:
        return sys._getframe(0)

    fr2 = Frame(f2("a", "b", "c"))
    assert fr2.getargs(var=True) == [("x", "a"), ("y", ("b", "c"))]

    def f3(x, **z) -> FrameType:
        return sys._getframe(0)

    fr3 = Frame(f3("a", b="c"))
    assert fr3.getargs(var=True) == [("x", "a"), ("z", {"b": "c"})]

    def f4(x, *y, **z) -> FrameType:
        return sys._getframe(0)

    fr4 = Frame(f4("a", "b", c="d"))
    assert fr4.getargs(var=True) == [("x", "a"), ("y", ("b",)), ("z", {"c": "d"})] 
Example #5
Source File: inspect.py    From BinderFilter with MIT License 6 votes vote down vote up
def isframe(object):
    """Return true if the object is a frame object.

    Frame objects provide these attributes:
        f_back          next outer frame object (this frame's caller)
        f_builtins      built-in namespace seen by this frame
        f_code          code object being executed in this frame
        f_exc_traceback traceback if raised in this frame, or None
        f_exc_type      exception type if raised in this frame, or None
        f_exc_value     exception value if raised in this frame, or None
        f_globals       global namespace seen by this frame
        f_lasti         index of last attempted instruction in bytecode
        f_lineno        current line number in Python source code
        f_locals        local namespace seen by this frame
        f_restricted    0 or 1 if frame is in restricted execution mode
        f_trace         tracing function for this frame, or None"""
    return isinstance(object, types.FrameType) 
Example #6
Source File: inspect.py    From Computable with MIT License 6 votes vote down vote up
def isframe(object):
    """Return true if the object is a frame object.

    Frame objects provide these attributes:
        f_back          next outer frame object (this frame's caller)
        f_builtins      built-in namespace seen by this frame
        f_code          code object being executed in this frame
        f_exc_traceback traceback if raised in this frame, or None
        f_exc_type      exception type if raised in this frame, or None
        f_exc_value     exception value if raised in this frame, or None
        f_globals       global namespace seen by this frame
        f_lasti         index of last attempted instruction in bytecode
        f_lineno        current line number in Python source code
        f_locals        local namespace seen by this frame
        f_restricted    0 or 1 if frame is in restricted execution mode
        f_trace         tracing function for this frame, or None"""
    return isinstance(object, types.FrameType) 
Example #7
Source File: inspect.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def isframe(object):
    """Return true if the object is a frame object.

    Frame objects provide these attributes:
        f_back          next outer frame object (this frame's caller)
        f_builtins      built-in namespace seen by this frame
        f_code          code object being executed in this frame
        f_exc_traceback traceback if raised in this frame, or None
        f_exc_type      exception type if raised in this frame, or None
        f_exc_value     exception value if raised in this frame, or None
        f_globals       global namespace seen by this frame
        f_lasti         index of last attempted instruction in bytecode
        f_lineno        current line number in Python source code
        f_locals        local namespace seen by this frame
        f_restricted    0 or 1 if frame is in restricted execution mode
        f_trace         tracing function for this frame, or None"""
    return isinstance(object, types.FrameType) 
Example #8
Source File: inspect.py    From oss-ftp with MIT License 6 votes vote down vote up
def isframe(object):
    """Return true if the object is a frame object.

    Frame objects provide these attributes:
        f_back          next outer frame object (this frame's caller)
        f_builtins      built-in namespace seen by this frame
        f_code          code object being executed in this frame
        f_exc_traceback traceback if raised in this frame, or None
        f_exc_type      exception type if raised in this frame, or None
        f_exc_value     exception value if raised in this frame, or None
        f_globals       global namespace seen by this frame
        f_lasti         index of last attempted instruction in bytecode
        f_lineno        current line number in Python source code
        f_locals        local namespace seen by this frame
        f_restricted    0 or 1 if frame is in restricted execution mode
        f_trace         tracing function for this frame, or None"""
    return isinstance(object, types.FrameType) 
Example #9
Source File: utils.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_source_context(
    frame,  # type: FrameType
    tb_lineno,  # type: int
):
    # type: (...) -> Tuple[List[Annotated[str]], Optional[Annotated[str]], List[Annotated[str]]]
    try:
        abs_path = frame.f_code.co_filename  # type: Optional[str]
    except Exception:
        abs_path = None
    try:
        module = frame.f_globals["__name__"]
    except Exception:
        return [], None, []
    try:
        loader = frame.f_globals["__loader__"]
    except Exception:
        loader = None
    lineno = tb_lineno - 1
    if lineno is not None and abs_path:
        return get_lines_from_file(abs_path, lineno, loader, module)
    return [], None, [] 
Example #10
Source File: utils.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def should_hide_frame(frame):
    # type: (FrameType) -> bool
    try:
        mod = frame.f_globals["__name__"]
        if mod.startswith("sentry_sdk."):
            return True
    except (AttributeError, KeyError):
        pass

    for flag_name in "__traceback_hide__", "__tracebackhide__":
        try:
            if frame.f_locals[flag_name]:
                return True
        except Exception:
            pass

    return False 
Example #11
Source File: _pydev_inspect.py    From PyDev.Debugger with Eclipse Public License 1.0 6 votes vote down vote up
def isframe(object):
    """Return true if the object is a frame object.

    Frame objects provide these attributes:
        f_back          next outer frame object (this frame's caller)
        f_builtins      built-in namespace seen by this frame
        f_code          code object being executed in this frame
        f_exc_traceback traceback if raised in this frame, or None
        f_exc_type      exception type if raised in this frame, or None
        f_exc_value     exception value if raised in this frame, or None
        f_globals       global namespace seen by this frame
        f_lasti         index of last attempted instruction in bytecode
        f_lineno        current line number in Python source code
        f_locals        local namespace seen by this frame
        f_restricted    0 or 1 if frame is in restricted execution mode
        f_trace         tracing function for this frame, or None"""
    return isinstance(object, types.FrameType) 
Example #12
Source File: inspect.py    From pmatic with GNU General Public License v2.0 6 votes vote down vote up
def isframe(object):
    """Return true if the object is a frame object.

    Frame objects provide these attributes:
        f_back          next outer frame object (this frame's caller)
        f_builtins      built-in namespace seen by this frame
        f_code          code object being executed in this frame
        f_exc_traceback traceback if raised in this frame, or None
        f_exc_type      exception type if raised in this frame, or None
        f_exc_value     exception value if raised in this frame, or None
        f_globals       global namespace seen by this frame
        f_lasti         index of last attempted instruction in bytecode
        f_lineno        current line number in Python source code
        f_locals        local namespace seen by this frame
        f_restricted    0 or 1 if frame is in restricted execution mode
        f_trace         tracing function for this frame, or None"""
    return isinstance(object, types.FrameType) 
Example #13
Source File: objgraph.py    From exaddos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def short_repr(obj):
    if isinstance(obj, (type, types.ModuleType, types.BuiltinMethodType,
                        types.BuiltinFunctionType)):
        return obj.__name__
    if isinstance(obj, types.MethodType):
        try:
            if obj.__self__ is not None:
                return obj.__func__.__name__ + ' (bound)'
            else:
                return obj.__func__.__name__
        except AttributeError:
            # Python < 2.6 compatibility
            if obj.im_self is not None:
                return obj.im_func.__name__ + ' (bound)'
            else:
                return obj.im_func.__name__

    if isinstance(obj, types.FrameType):
        return '%s:%s' % (obj.f_code.co_filename, obj.f_lineno)
    if isinstance(obj, (tuple, list, dict, set)):
        return '%d items' % len(obj)
    return repr(obj)[:40] 
Example #14
Source File: _assertionold.py    From python-netsurv with MIT License 6 votes vote down vote up
def interpret(source, frame, should_fail=False):
    module = Interpretable(parse(source, 'exec').node)
    #print "got module", module
    if isinstance(frame, types.FrameType):
        frame = py.code.Frame(frame)
    try:
        module.run(frame)
    except Failure:
        e = sys.exc_info()[1]
        return getfailure(e)
    except passthroughex:
        raise
    except:
        import traceback
        traceback.print_exc()
    if should_fail:
        return ("(assertion failed, but when it was re-run for "
                "printing intermediate values, it did not fail.  Suggestions: "
                "compute assert expression before the assert or use --nomagic)")
    else:
        return None 
Example #15
Source File: _assertionold.py    From python-netsurv with MIT License 6 votes vote down vote up
def interpret(source, frame, should_fail=False):
    module = Interpretable(parse(source, 'exec').node)
    #print "got module", module
    if isinstance(frame, types.FrameType):
        frame = py.code.Frame(frame)
    try:
        module.run(frame)
    except Failure:
        e = sys.exc_info()[1]
        return getfailure(e)
    except passthroughex:
        raise
    except:
        import traceback
        traceback.print_exc()
    if should_fail:
        return ("(assertion failed, but when it was re-run for "
                "printing intermediate values, it did not fail.  Suggestions: "
                "compute assert expression before the assert or use --nomagic)")
    else:
        return None 
Example #16
Source File: inspect.py    From meddle with MIT License 6 votes vote down vote up
def isframe(object):
    """Return true if the object is a frame object.

    Frame objects provide these attributes:
        f_back          next outer frame object (this frame's caller)
        f_builtins      built-in namespace seen by this frame
        f_code          code object being executed in this frame
        f_exc_traceback traceback if raised in this frame, or None
        f_exc_type      exception type if raised in this frame, or None
        f_exc_value     exception value if raised in this frame, or None
        f_globals       global namespace seen by this frame
        f_lasti         index of last attempted instruction in bytecode
        f_lineno        current line number in Python source code
        f_locals        local namespace seen by this frame
        f_restricted    0 or 1 if frame is in restricted execution mode
        f_trace         tracing function for this frame, or None"""
    return isinstance(object, types.FrameType) 
Example #17
Source File: _assertionold.py    From py with MIT License 6 votes vote down vote up
def interpret(source, frame, should_fail=False):
    module = Interpretable(parse(source, 'exec').node)
    #print "got module", module
    if isinstance(frame, types.FrameType):
        frame = py.code.Frame(frame)
    try:
        module.run(frame)
    except Failure:
        e = sys.exc_info()[1]
        return getfailure(e)
    except passthroughex:
        raise
    except:
        import traceback
        traceback.print_exc()
    if should_fail:
        return ("(assertion failed, but when it was re-run for "
                "printing intermediate values, it did not fail.  Suggestions: "
                "compute assert expression before the assert or use --nomagic)")
    else:
        return None 
Example #18
Source File: utils.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def isNonPrimitiveInstance(x):
        return isinstance(x,types.InstanceType) or not isinstance(x,(float,int,long,type,tuple,list,dict,bool,unicode,str,buffer,complex,slice,types.NoneType,
                    types.FunctionType,types.LambdaType,types.CodeType,types.GeneratorType,
                    types.ClassType,types.UnboundMethodType,types.MethodType,types.BuiltinFunctionType,
                    types.BuiltinMethodType,types.ModuleType,types.FileType,types.XRangeType,
                    types.TracebackType,types.FrameType,types.EllipsisType,types.DictProxyType,
                    types.NotImplementedType,types.GetSetDescriptorType,types.MemberDescriptorType
                    )) 
Example #19
Source File: sandbox.py    From Financial-Portfolio-Flask with MIT License 5 votes vote down vote up
def is_internal_attribute(obj, attr):
    """Test if the attribute given is an internal python attribute.  For
    example this function returns `True` for the `func_code` attribute of
    python objects.  This is useful if the environment method
    :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    """
    if isinstance(obj, types.FunctionType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES:
            return True
    elif isinstance(obj, types.MethodType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
           attr in UNSAFE_METHOD_ATTRIBUTES:
            return True
    elif isinstance(obj, type):
        if attr == 'mro':
            return True
    elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
        return True
    elif isinstance(obj, types.GeneratorType):
        if attr in UNSAFE_GENERATOR_ATTRIBUTES:
            return True
    return attr.startswith('__') 
Example #20
Source File: sandbox.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def is_internal_attribute(obj, attr):
    """Test if the attribute given is an internal python attribute.  For
    example this function returns `True` for the `func_code` attribute of
    python objects.  This is useful if the environment method
    :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    """
    if isinstance(obj, types.FunctionType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES:
            return True
    elif isinstance(obj, types.MethodType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
           attr in UNSAFE_METHOD_ATTRIBUTES:
            return True
    elif isinstance(obj, type):
        if attr == 'mro':
            return True
    elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
        return True
    elif isinstance(obj, types.GeneratorType):
        if attr in UNSAFE_GENERATOR_ATTRIBUTES:
            return True
    elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType):
        if attr in UNSAFE_COROUTINE_ATTRIBUTES:
            return True
    elif hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType):
        if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
            return True
    return attr.startswith('__') 
Example #21
Source File: View.py    From guppy3 with MIT License 5 votes vote down vote up
def heapg(self, rma=1):
        # Almost the same as gc.get_objects(),
        # except:
        # 1. calls gc.collect() first (twice)
        # 2. removes objects of type gchook
        # 3. removes objects of type ClearCallback
        # 4. removes all objects of type types.FrameType
        # 5. removes all objects of weakref type
        # 6. If rma = 1,
        #    removes all that is in the reachable heap
        #    except what is in the set itself.

        # . wraps the result in an IdSet

        self.gc.collect()
        self.gc.collect()
        objs = self.gc.get_objects()
        cli = self.hv.cli_type()
        objs = cli.select(objs, self.gchook_type, '!=')
        objs = cli.select(objs, ClearCallback, '!=')
        objs = cli.select(objs, self._root.types.FrameType, '!=')
        objs = cli.select(objs, self._root.weakref.ReferenceType, '!=')
        r = self.retset(objs)
        del cli, objs

        if rma:
            r = (r - self.idset(self.heapyc.HeapView(
                self.heapyc.RootState,
                self.heapdefs
            ).reachable_x(
                self.immnodeset([self.heapyc.RootState]),
                self.observation_containers()
            ))
            )

        return r 
Example #22
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _stackless_schedule_cb(self, prev, next):
        current = stackless.getcurrent()
        if not current:
            return
        current_tf = current.trace_function
        
        try:
            current.trace_function = None
            self.stepping = STEPPING_NONE
            
            # If the current frame has no trace function, we may need to get it
            # from the previous frame, depending on how we ended up in the
            # callback.
            if current_tf is None:
                f_back = current.frame.f_back
                if f_back is not None:
                    current_tf = f_back.f_trace

            if next is not None:
                # Assign our trace function to the current stack
                f = next.frame
                if next is current:
                    f = f.f_back
                while f:
                    if isinstance(f, types.FrameType):
                        f.f_trace = self.trace_func
                    f = f.f_back
                next.trace_function = self.trace_func
        finally:
            current.trace_function = current_tf 
Example #23
Source File: frame_formatting.py    From stackprinter with MIT License 5 votes vote down vote up
def __call__(self, frame, lineno=None):
        """
        Render a single stack frame or traceback entry


        Params
        ----

        frame: Frame object, Traceback object (or FrameInfo tuple)
            The frame or traceback entry to be formatted.

            The only difference between passing a frame or a traceback object is
            which line gets highlighted in the source listing: For a frame, it's
            the currently executed line; for a traceback, it's the line where an
            error occurred. (technically: `frame.f_lineno` vs. `tb.tb_lineno`)

            The third option is interesting only if you're planning to format
            one frame multiple different ways: It is a little faster to format a
            pre-chewed verion of the frame, since non-formatting-specific steps
            like "finding the source code", "finding all the variables" etc only
            need to be done once per frame. So, this method also accepts the raw
            results of `extraction.get_info()` of type FrameInfo. In that case,
            this method will really just do formatting, no more chewing.

        lineno: int
            override which line gets highlighted
        """
        accepted_types = (types.FrameType, types.TracebackType, ex.FrameInfo)
        if not isinstance(frame, accepted_types):
            raise ValueError("Expected one of these types: "
                             "%s. Got %r" % (accepted_types, frame))

        try:
            finfo = ex.get_info(frame, lineno)

            return self._format_frame(finfo)
        except Exception as exc:
            # If we crash, annotate the exception with the thing
            # we were trying to format, for debug/logging purposes.
            exc.where = frame
            raise 
Example #24
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _stackless_schedule_cb(self, prev, next):
        current = stackless.getcurrent()
        if not current:
            return
        current_tf = current.trace_function
        
        try:
            current.trace_function = None
            self.stepping = STEPPING_NONE
            
            # If the current frame has no trace function, we may need to get it
            # from the previous frame, depending on how we ended up in the
            # callback.
            if current_tf is None:
                f_back = current.frame.f_back
                if f_back is not None:
                    current_tf = f_back.f_trace

            if next is not None:
                # Assign our trace function to the current stack
                f = next.frame
                if next is current:
                    f = f.f_back
                while f:
                    if isinstance(f, types.FrameType):
                        f.f_trace = self.trace_func
                    f = f.f_back
                next.trace_function = self.trace_func
        finally:
            current.trace_function = current_tf 
Example #25
Source File: utils.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def isNonPrimitiveInstance(x):
        return not isinstance(x,(float,int,type,tuple,list,dict,str,bytes,complex,bool,slice,_rl_NoneType,
            types.FunctionType,types.LambdaType,types.CodeType,
            types.MappingProxyType,types.SimpleNamespace,
            types.GeneratorType,types.MethodType,types.BuiltinFunctionType,
            types.BuiltinMethodType,types.ModuleType,types.TracebackType,
            types.FrameType,types.GetSetDescriptorType,types.MemberDescriptorType)) 
Example #26
Source File: inspect.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def isframe(object):
    """Return true if the object is a frame object.

    Frame objects provide these attributes:
        f_back          next outer frame object (this frame's caller)
        f_builtins      built-in namespace seen by this frame
        f_code          code object being executed in this frame
        f_globals       global namespace seen by this frame
        f_lasti         index of last attempted instruction in bytecode
        f_lineno        current line number in Python source code
        f_locals        local namespace seen by this frame
        f_trace         tracing function for this frame, or None"""
    return isinstance(object, types.FrameType) 
Example #27
Source File: sandbox.py    From pySINDy with MIT License 5 votes vote down vote up
def is_internal_attribute(obj, attr):
    """Test if the attribute given is an internal python attribute.  For
    example this function returns `True` for the `func_code` attribute of
    python objects.  This is useful if the environment method
    :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    """
    if isinstance(obj, types.FunctionType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES:
            return True
    elif isinstance(obj, types.MethodType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
           attr in UNSAFE_METHOD_ATTRIBUTES:
            return True
    elif isinstance(obj, type):
        if attr == 'mro':
            return True
    elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
        return True
    elif isinstance(obj, types.GeneratorType):
        if attr in UNSAFE_GENERATOR_ATTRIBUTES:
            return True
    elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType):
        if attr in UNSAFE_COROUTINE_ATTRIBUTES:
            return True
    elif hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType):
        if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
            return True
    return attr.startswith('__') 
Example #28
Source File: inspect.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def getlineno(frame):
    """Get the line number from a frame object, allowing for optimization."""
    # FrameType.f_lineno is now a descriptor that grovels co_lnotab
    return frame.f_lineno 
Example #29
Source File: test_tasks.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_corowrapper_mocks_generator(self):

        def check():
            # A function that asserts various things.
            # Called twice, with different debug flag values.

            @asyncio.coroutine
            def coro():
                # The actual coroutine.
                self.assertTrue(gen.gi_running)
                yield from fut

            # A completed Future used to run the coroutine.
            fut = asyncio.Future(loop=self.loop)
            fut.set_result(None)

            # Call the coroutine.
            gen = coro()

            # Check some properties.
            self.assertTrue(asyncio.iscoroutine(gen))
            self.assertIsInstance(gen.gi_frame, types.FrameType)
            self.assertFalse(gen.gi_running)
            self.assertIsInstance(gen.gi_code, types.CodeType)

            # Run it.
            self.loop.run_until_complete(gen)

            # The frame should have changed.
            self.assertIsNone(gen.gi_frame)

        # Test with debug flag cleared.
        with set_coroutine_debug(False):
            check()

        # Test with debug flag set.
        with set_coroutine_debug(True):
            check() 
Example #30
Source File: utils.py    From paasta with Apache License 2.0 5 votes vote down vote up
def handle_timeout(self, signum: int, frame: FrameType) -> None:
        raise TimeoutError(self.error_message)