Python inspect.FrameInfo() Examples

The following are 10 code examples of inspect.FrameInfo(). 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: code_pointer.py    From dagster with Apache License 2.0 6 votes vote down vote up
def get_python_file_from_previous_stack_frame():
    '''inspect.stack() lets us introspect the call stack; inspect.stack()[1] is the previous
    stack frame.

    In Python < 3.5, this is just a tuple, of which the python file of the previous frame is the 1st
    element.

    In Python 3.5+, this is a FrameInfo namedtuple instance; the python file of the previous frame
    remains the 1st element.
    '''

    # Since this is now a function in this file, we need to go back two hops to find the
    # callsite file.
    previous_stack_frame = inspect.stack(0)[2]

    # See: https://docs.python.org/3/library/inspect.html
    if sys.version_info.major == 3 and sys.version_info.minor >= 5:
        check.inst(previous_stack_frame, inspect.FrameInfo)
    else:
        check.inst(previous_stack_frame, tuple)

    python_file = previous_stack_frame[1]
    return os.path.abspath(python_file) 
Example #2
Source File: _error_reporting.py    From pyquil with Apache License 2.0 6 votes vote down vote up
def dump_error(self, exception: Exception, trace: List[inspect.FrameInfo]) -> None:
        warn_msg = """
>>> PYQUIL_PROTECT <<<
An uncaught exception was raised in a function wrapped in pyquil_protect.  We are writing out a
log file to "{}".

Along with a description of what you were doing when the error occurred, send this file to
Rigetti Computing support by email at support@rigetti.com for assistance.
>>> PYQUIL_PROTECT <<<
""".format(
            os.path.abspath(self.filename)
        )

        _log.warning(warn_msg)

        report = self.generate_report(exception, trace)

        # overwrite any existing log file
        fh = open(self.filename, "w")
        fh.write(json.dumps(report, default=json_serialization_helper))
        fh.close() 
Example #3
Source File: tracing.py    From returns with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _get_trace(_self: _Failure) -> Optional[List[FrameInfo]]:
    """
    Function to be used on Monkey Patching.

    This function is the substitute for '_get_trace' method from ``_Failure``
    class on Monkey Patching promoted by
    :func:`returns.primitives.tracing.collect_traces` function.

    We get all the call stack from the current call and return it from the
    third position, to avoid two non-useful calls on the call stack.
    Those non-useful calls are a call to this function and a call to `__init__`
    method from ``_Failure`` class. We're just interested in the call stack
    ending on ``Failure`` function call!

    See also:
        https://github.com/dry-python/returns/issues/409

    """
    current_stack = stack()
    return current_stack[2:] 
Example #4
Source File: frame_operations.py    From ver-observer with GNU General Public License v3.0 5 votes vote down vote up
def real_frame_extract(subframe, filepath, lineno):
    """
    :type subframe: inspect.FrameInfo
    :rtype: inspect.FrameInfo
    """
    frames = inspect.getouterframes(subframe)
    for frame in frames:
        if PY2:
            if frame[1] == filepath and frame[2] == lineno:
                return frame[0]  # type: inspect.FrameInfo
        elif frame.filename == filepath and frame.lineno == lineno:
            return frame.frame  # type: inspect.FrameInfo
    
    return None 
Example #5
Source File: _error_reporting.py    From pyquil with Apache License 2.0 5 votes vote down vote up
def generate_report(self, exception: Exception, trace: List[inspect.FrameInfo]) -> ErrorReport:
        """
        Handle an error generated in a routine decorated with the pyQuil error handler.

        :param exception: Exception object that generated this error.
        :param trace: inspect.trace object from the frame that caught the error.
        :return: ErrorReport object
        """
        stack_trace = [
            StacktraceFrame(
                name=item.function,
                filename=item.filename,
                line_number=item.lineno,
                locals={
                    k: serialize_object_for_logging(v) for (k, v) in item.frame.f_locals.items()
                },
            )
            for item in trace
        ]

        system_info = generate_system_info()

        report = ErrorReport(
            stack_trace=stack_trace,
            timestamp=datetime.utcnow(),
            exception=exception,
            system_info=system_info,
            call_log=flatten_log(self.log),
        )

        return report 
Example #6
Source File: result.py    From returns with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def trace(self) -> Optional[List[FrameInfo]]:
        """Returns a list with stack trace when :func:`~Failure` was called."""
        return self._trace 
Example #7
Source File: result.py    From returns with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _get_trace(self) -> Optional[List[FrameInfo]]:
        """Method that will be monkey patched when trace is active."""
        return None  # noqa: WPS324 
Example #8
Source File: io.py    From returns with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def trace(self) -> Optional[List[FrameInfo]]:
        """Returns a list with stack trace when :func:`~Failure` was called."""
        return self._inner_value.trace 
Example #9
Source File: tracing.py    From returns with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def collect_traces(
    function: Optional[_FunctionType] = None,
) -> Union[_FunctionType, ContextManager[None]]:  # noqa: DAR101, DAR201, DAR301
    """
    Context Manager/Decorator to active traces collect to the Failures.

    .. code:: python

        >>> from inspect import FrameInfo

        >>> from returns.io import IOResult
        >>> from returns.result import Result
        >>> from returns.primitives.tracing import collect_traces

        >>> with collect_traces():
        ...     traced_failure = Result.from_failure('Traced Failure')
        >>> non_traced_failure = IOResult.from_failure('Non Traced Failure')

        >>> assert non_traced_failure.trace is None
        >>> assert isinstance(traced_failure.trace, list)
        >>> assert all(isinstance(trace_line, FrameInfo) for trace_line in traced_failure.trace)

        >>> for trace_line in traced_failure.trace:
        ...     print(f'{trace_line.filename}:{trace_line.lineno} in `{trace_line.function}`') # doctest: +SKIP
        ...
        /returns/returns/result.py:525 in `Failure`
        /returns/returns/result.py:322 in `from_failure`
        /example_folder/example.py:1 in `<module>`
        # doctest: # noqa: DAR301, E501

    """
    @contextmanager
    def factory() -> Iterator[None]:
        unpatched_get_trace = getattr(_Failure, '_get_trace')  # noqa: B009
        substitute_get_trace = types.MethodType(_get_trace, _Failure)
        setattr(_Failure, '_get_trace', substitute_get_trace)  # noqa: B010
        try:  # noqa: WPS501
            yield
        finally:
            setattr(_Failure, '_get_trace', unpatched_get_trace)  # noqa: B010
    return factory()(function) if function else factory() 
Example #10
Source File: test_logs.py    From kytos with MIT License 5 votes vote down vote up
def _set_filename(self, filename):
        """Mock the NApp's main.py file path."""
        # Put the filename in the call stack
        frame = FrameInfo(None, filename, None, None, None, None)
        self._inspect_patcher = patch('kytos.core.logs.inspect')
        inspect = self._inspect_patcher.start()
        inspect.stack.return_value = [frame]