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: record.py From recipes-py with Apache License 2.0 | 6 votes |
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 #2
Source File: _assertionold.py From py with MIT License | 6 votes |
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 #3
Source File: _assertionold.py From python-netsurv with MIT License | 6 votes |
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 #4
Source File: _assertionold.py From python-netsurv with MIT License | 6 votes |
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 #5
Source File: inspect.py From meddle with MIT License | 6 votes |
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: objgraph.py From exaddos with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #7
Source File: utils.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
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 #8
Source File: utils.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
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 #9
Source File: inspect.py From ironpython2 with Apache License 2.0 | 6 votes |
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 #10
Source File: logging.py From fastapi-realworld-example-app with MIT License | 6 votes |
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 #11
Source File: inspect.py From BinderFilter with MIT License | 6 votes |
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 Computable with MIT License | 6 votes |
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: inspect.py From oss-ftp with MIT License | 6 votes |
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 #14
Source File: _pydev_inspect.py From PyDev.Debugger with Eclipse Public License 1.0 | 6 votes |
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 #15
Source File: inspect.py From pmatic with GNU General Public License v2.0 | 6 votes |
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 #16
Source File: test_code.py From pytest with MIT License | 6 votes |
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 #17
Source File: inspect.py From jawfish with MIT License | 5 votes |
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 #18
Source File: inspect.py From jawfish with MIT License | 5 votes |
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 #19
Source File: sandbox.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
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 #20
Source File: sandbox.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
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: sandbox.py From recruit with Apache License 2.0 | 5 votes |
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 #22
Source File: sandbox.py From recruit with Apache License 2.0 | 5 votes |
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 #23
Source File: sandbox.py From jbox with MIT License | 5 votes |
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 #24
Source File: inspect.py From meddle with MIT License | 5 votes |
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 #25
Source File: objgraph.py From exaddos with BSD 3-Clause "New" or "Revised" License | 5 votes |
def edge_label(source, target): if isinstance(target, dict) and target is getattr(source, '__dict__', None): return ' [label="__dict__",weight=10]' if isinstance(source, types.FrameType): if target is source.f_locals: return ' [label="f_locals",weight=10]' if target is source.f_globals: return ' [label="f_globals",weight=10]' if isinstance(source, types.MethodType): try: if target is source.__self__: return ' [label="__self__",weight=10]' if target is source.__func__: return ' [label="__func__",weight=10]' except AttributeError: # Python < 2.6 compatibility if target is source.im_self: return ' [label="im_self",weight=10]' if target is source.im_func: return ' [label="im_func",weight=10]' if isinstance(source, types.FunctionType): for k in dir(source): if target is getattr(source, k): return ' [label="%s",weight=10]' % quote(k) if isinstance(source, dict): for k, v in iteritems(source): if v is target: if isinstance(k, basestring) and is_identifier(k): return ' [label="%s",weight=2]' % quote(k) else: return ' [label="%s"]' % quote(type(k).__name__ + "\n" + safe_repr(k)) return ''
Example #26
Source File: _plugin.py From tmppy with Apache License 2.0 | 5 votes |
def _extract_branch(self, frame: FrameType): branch = frame.f_locals['branch'] assert isinstance(branch, SourceBranch) return branch
Example #27
Source File: _plugin.py From tmppy with Apache License 2.0 | 5 votes |
def dynamic_source_filename(self, filename: str, frame: FrameType): branch = self._extract_branch(frame) return branch.file_name
Example #28
Source File: _plugin.py From tmppy with Apache License 2.0 | 5 votes |
def line_number_range(self, frame: FrameType): branch = self._extract_branch(frame) if branch.source_line > 0: return branch.source_line, branch.source_line else: return -1, -1
Example #29
Source File: utils.py From sentry-python with BSD 2-Clause "Simplified" License | 5 votes |
def serialize_frame(frame, tb_lineno=None, with_locals=True): # type: (FrameType, Optional[int], bool) -> Dict[str, Any] f_code = getattr(frame, "f_code", None) if not f_code: abs_path = None function = None else: abs_path = frame.f_code.co_filename function = frame.f_code.co_name try: module = frame.f_globals["__name__"] except Exception: module = None if tb_lineno is None: tb_lineno = frame.f_lineno pre_context, context_line, post_context = get_source_context(frame, tb_lineno) rv = { "filename": filename_for_module(module, abs_path) or None, "abs_path": os.path.abspath(abs_path) if abs_path else None, "function": function or "<unknown>", "module": module, "lineno": tb_lineno, "pre_context": pre_context, "context_line": context_line, "post_context": post_context, } # type: Dict[str, Any] if with_locals: rv["vars"] = frame.f_locals return rv
Example #30
Source File: utils.py From sentry-python with BSD 2-Clause "Simplified" License | 5 votes |
def current_stacktrace(with_locals=True): # type: (bool) -> Any __tracebackhide__ = True frames = [] f = sys._getframe() # type: Optional[FrameType] while f is not None: if not should_hide_frame(f): frames.append(serialize_frame(f, with_locals=with_locals)) f = f.f_back frames.reverse() return {"frames": frames}