PyGuide

Learn Python with practical tutorials and code examples

Code Snippet Intermediate
• Updated Jul 22, 2024

Python Error Frame Inspection Code Examples

Ready-to-use Python code snippets for inspecting error frames, analyzing stack traces, and debugging frame-related issues effectively.

Python Error Frame Inspection Code Examples

When Python can error frame issues arise, having ready-to-use code snippets for inspection and debugging saves valuable time. These practical examples help you analyze error frames, extract meaningful information, and implement robust error handling.

Basic Frame Inspection #

Get Current Frame Information #

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Trace Function Call Stack #

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Exception Frame Analysis #

Analyze Exception Traceback Frames #

import traceback
import sys

class FrameAnalyzer:
    """Utility class for analyzing exception frames"""
    
    @staticmethod
    def extract_frame_details(exception):
        """Extract detailed information from exception frames"""
        frames = []
        tb = exception.__traceback__
        
        while tb is not None:
            frame = tb.tb_frame
            frame_details = {
                'filename': frame.f_code.co_filename,
                'function_name': frame.f_code.co_name,
                'line_number': tb.tb_lineno,
                'code_context': FrameAnalyzer._get_code_context(frame, tb.tb_lineno),
                'local_vars': {k: repr(v) for k, v in frame.f_locals.items() 
                              if not k.startswith('__')}
            }
            frames.append(frame_details)
            tb = tb.tb_next
            
        return frames
    
    @staticmethod
    def _get_code_context(frame, line_number):
        """Get code context around the error line"""
        try:
            import linecache
            filename = frame.f_code.co_filename
            lines = []
            for i in range(max(1, line_number - 2), line_number + 3):
                line = linecache.getline(filename, i).rstrip()
                marker = ' -> ' if i == line_number else '    '
                lines.append(f"{marker}{i}: {line}")
            return '\n'.join(lines)
        except:
            return "Code context unavailable"
    
    @staticmethod
    def print_detailed_traceback(exception):
        """Print a detailed analysis of exception frames"""
        print(f"Exception Type: {type(exception).__name__}")
        print(f"Exception Message: {str(exception)}")
        print("\nDetailed Frame Analysis:")
        print("-" * 50)
        
        frames = FrameAnalyzer.extract_frame_details(exception)
        for i, frame in enumerate(frames):
            print(f"\nFrame {i}: {frame['function_name']} ")
            print(f"File: {frame['filename'].split('/')[-1]}:{frame['line_number']}")
            print(f"Local Variables: {frame['local_vars']}")
            if frame['code_context']:
                print(f"Code Context:\n{frame['code_context']}")

# Usage example
def problematic_function():
    x = 10
    y = 0
    result = x / y  # This will cause a ZeroDivisionError
    return result

try:
    problematic_function()
except Exception as e:
    FrameAnalyzer.print_detailed_traceback(e)

Custom Exception with Frame Preservation #

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Frame-Safe Debugging Tools #

Safe Frame Inspector #

import sys
import weakref
from contextlib import contextmanager

class SafeFrameInspector:
    """Memory-safe frame inspection utility"""
    
    def __init__(self):
        self.frame_refs = []
    
    @contextmanager
    def inspect_frame(self, frame=None):
        """Context manager for safe frame inspection"""
        if frame is None:
            frame = sys._getframe(1)
        
        # Use weak reference to avoid cycles
        frame_ref = weakref.ref(frame)
        self.frame_refs.append(frame_ref)
        
        try:
            yield frame
        finally:
            # Clean up reference
            if frame_ref in self.frame_refs:
                self.frame_refs.remove(frame_ref)
            del frame
    
    def get_frame_summary(self, frame):
        """Get safe summary of frame information"""
        return {
            'function': getattr(frame.f_code, 'co_name', 'unknown'),
            'filename': getattr(frame.f_code, 'co_filename', 'unknown').split('/')[-1],
            'line': getattr(frame, 'f_lineno', 0),
            'var_count': len(getattr(frame, 'f_locals', {}))
        }
    
    def cleanup(self):
        """Clean up all frame references"""
        self.frame_refs.clear()

# Usage
inspector = SafeFrameInspector()

def debug_function():
    x = 42
    y = "hello"
    
    with inspector.inspect_frame() as frame:
        summary = inspector.get_frame_summary(frame)
        print("Frame Summary:")
        for key, value in summary.items():
            print(f"  {key}: {value}")

debug_function()
inspector.cleanup()

Error Frame Logger #

🐍 Try it yourself

Output:
Click "Run Code" to see the output

Advanced Frame Utilities #

Frame State Capture #

import pickle
import base64
from types import FrameType

class FrameStateCapture:
    """Capture and serialize frame state for debugging"""
    
    @staticmethod
    def capture_frame_state(frame):
        """Capture serializable frame state"""
        if not isinstance(frame, FrameType):
            raise TypeError("Expected frame object")
        
        # Extract serializable information
        state = {
            'function_name': frame.f_code.co_name,
            'filename': frame.f_code.co_filename,
            'line_number': frame.f_lineno,
            'argument_names': frame.f_code.co_varnames[:frame.f_code.co_argcount],
            'local_vars': {},
            'global_vars': {}
        }
        
        # Capture serializable local variables
        for name, value in frame.f_locals.items():
            try:
                # Test if value is serializable
                pickle.dumps(value)
                state['local_vars'][name] = value
            except (pickle.PicklingError, TypeError):
                state['local_vars'][name] = f"<non-serializable: {type(value).__name__}>"
        
        # Capture relevant global variables
        for name, value in frame.f_globals.items():
            if not name.startswith('__') and name in frame.f_code.co_names:
                try:
                    pickle.dumps(value)
                    state['global_vars'][name] = value
                except (pickle.PicklingError, TypeError):
                    state['global_vars'][name] = f"<non-serializable: {type(value).__name__}>"
        
        return state
    
    @staticmethod
    def serialize_frame_state(frame_state):
        """Serialize frame state to base64 string"""
        serialized = pickle.dumps(frame_state)
        return base64.b64encode(serialized).decode('utf-8')
    
    @staticmethod
    def deserialize_frame_state(serialized_state):
        """Deserialize frame state from base64 string"""
        decoded = base64.b64decode(serialized_state.encode('utf-8'))
        return pickle.loads(decoded)

# Usage
def example_with_state_capture():
    x = 42
    y = [1, 2, 3]
    z = {"key": "value"}
    
    import inspect
    current_frame = inspect.currentframe()
    try:
        state = FrameStateCapture.capture_frame_state(current_frame)
        print("Captured frame state:")
        print(f"Function: {state['function_name']}")
        print(f"Local vars: {state['local_vars']}")
        
        # Serialize and deserialize
        serialized = FrameStateCapture.serialize_frame_state(state)
        deserialized = FrameStateCapture.deserialize_frame_state(serialized)
        print(f"Serialization successful: {state == deserialized}")
        
    finally:
        del current_frame

example_with_state_capture()

Summary #

These Python error frame inspection code examples provide practical tools for debugging when Python can error frame issues occur. Key utilities include:

  • Basic frame information extraction
  • Exception traceback analysis
  • Memory-safe frame inspection
  • Custom exception handling with frame preservation
  • Advanced frame state capture and serialization

Use these snippets to implement robust error handling and debugging capabilities in your Python applications.

Related Snippets

Snippet Advanced

Python Can Error Frame Analysis Code Examples

Ready-to-use Python code snippets for error frame analysis when Python can error frame issues occur. Complete debugging examples and utilities.

#python #error #frame +3
View Code
Syntax
Snippet Intermediate

Python Error Handling Code Snippets: Try-Except Examples

Ready-to-use Python error handling code snippets. Copy-paste examples for common error handling patterns and exception management.

#python #error #exception +2
View Code
Syntax
Snippet Intermediate

Python What Error to Raise: Code Examples and Patterns

Practical code snippets showing what error to raise in Python. Copy-paste examples for ValueError, TypeError, AttributeError, and custom exceptions.

#python #exceptions #raise +2
View Code
Syntax
Snippet Beginner

Python Indentation Error Fix Beginner Debugging Code Utilities

Ready-to-use Python code utilities for indentation error fix beginner debugging tips including detection scripts and automated fixing tools.

#python #indentation #debugging +3
View Code
Syntax