Module osbot_utils.helpers.trace.Trace_Call

Expand source code
import linecache
import sys
from functools import wraps

from osbot_utils.base_classes.Kwargs_To_Self                import Kwargs_To_Self
from osbot_utils.helpers.trace.Trace_Call__Config           import Trace_Call__Config, PRINT_MAX_STRING_LENGTH
from osbot_utils.helpers.trace.Trace_Call__Handler          import Trace_Call__Handler
from osbot_utils.helpers.trace.Trace_Call__Print_Lines      import Trace_Call__Print_Lines
from osbot_utils.helpers.trace.Trace_Call__Print_Traces     import Trace_Call__Print_Traces
from osbot_utils.helpers.trace.Trace_Call__View_Model       import Trace_Call__View_Model


def trace_calls(title         = None , print_traces = True , show_locals    = False, source_code          = False ,
                ignore        = None , include      = None , show_path      = False, duration_bigger_than = 0     ,
                max_string    = None , show_types   = False, show_duration  = False ,# show_caller    = False     ,         # todo: add back when show_caller is working again
                show_class    = False, contains     = None , show_internals = False, enabled              = True  ,
                extra_data    = False, show_lines   = False, print_lines    = False, show_types_padding   = None  , duration_padding=None):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            config_kwargs = dict(title=title, print_traces_on_exit=print_traces, print_locals=show_locals,
                                 capture_locals = show_locals,
                                 trace_capture_source_code=source_code, ignore_start_with=ignore,
                                 trace_capture_start_with=include, print_max_string_length=max_string,
                                 show_parent_info=show_types, show_method_class=show_class,
                                 show_source_code_path=show_path,
                                 capture_duration=show_duration, print_duration= show_duration,
                                 with_duration_bigger_than=duration_bigger_than,
                                 trace_capture_contains=contains, trace_show_internals=show_internals,
                                 capture_extra_data=extra_data,
                                 print_padding_parent_info= show_types_padding, print_padding_duration=duration_padding,
                                 print_lines_on_exit=print_lines, trace_enabled=enabled,
                                 trace_capture_lines=show_lines or print_lines)

            config = (Trace_Call__Config().update_from_kwargs (**config_kwargs))

            with Trace_Call(config=config):
                result = func(*args, **kwargs)
                return result
        return wrapper
    return decorator

class Trace_Call(Kwargs_To_Self):

    config             : Trace_Call__Config
    started            : bool
    prev_trace_function: None

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.trace_call_handler                                 = Trace_Call__Handler     (config=self.config)
        self.trace_call_print_traces                            = Trace_Call__Print_Traces(config=self.config)
        self.trace_call_view_model                              = Trace_Call__View_Model  ()
        self.config.print_traces_on_exit                        = self.config.print_traces_on_exit
        #self.config.trace_capture_start_with                    = self.config.capture_start_with       or []          # todo add a better way to set these to [] when then value is null
        self.config.trace_ignore_start_with                     = self.config.ignore_start_with        or []          #      probablty better done inside Kwargs_To_Self since it doesn't make sense for lists or dicts to have None value
        self.config.trace_capture_contains                      = self.config.trace_capture_contains   or []          #      and None will be quite common since we can use [] on method's params
        self.config.print_max_string_length                     = self.config.print_max_string_length  or PRINT_MAX_STRING_LENGTH
        self.stack                                              = self.trace_call_handler.stack
        #self.prev_trace_function                                = None                                                # Stores the previous trace function


    def __enter__(self):
        return self.on_enter()

    def __exit__(self, exc_type, exc_val, exc_tb):
        return self.on_exit()

    def on_enter(self):
        if self.config.trace_enabled:
            self.start()  # Start the tracing
        return self

    def on_exit(self):
        if self.config.trace_enabled:
            self.stop()  # Stop the tracing
            if self.config.print_traces_on_exit:
                self.print()
            if self.config.print_lines_on_exit:
                self.print_lines()

    def capture_all(self):
        self.config.trace_capture_all = True
        return self

    def view_data(self):
        return self.trace_call_view_model.create(self.stack)

    def print(self):
        view_model = self.view_data()
        self.trace_call_print_traces.print_traces(view_model)
        #self.print_lines()
        return view_model

    def print_lines(self):
        print()
        view_model = self.view_data()
        print_lines = Trace_Call__Print_Lines(config=self.config, view_model=view_model)
        print_lines.print_lines()

    def start(self):
        self.trace_call_handler.stack.add_node(title=self.trace_call_handler.config.title)
        self.prev_trace_function = sys.gettrace()
        self.started             = True                                                         # set this here so that it does show in the trace
        sys.settrace(self.trace_call_handler.trace_calls)                                       # Set the new trace function


    def stop(self):
        if self.started:
            sys.settrace(self.prev_trace_function)                                              # Restore the previous trace function
            self.stack.empty_stack()
            self.started = False

    def stats(self):
        return self.trace_call_handler.stats

    def stats_data(self):
        return self.trace_call_handler.stats.raw_call_stats

Functions

def trace_calls(title=None, print_traces=True, show_locals=False, source_code=False, ignore=None, include=None, show_path=False, duration_bigger_than=0, max_string=None, show_types=False, show_duration=False, show_class=False, contains=None, show_internals=False, enabled=True, extra_data=False, show_lines=False, print_lines=False, show_types_padding=None, duration_padding=None)
Expand source code
def trace_calls(title         = None , print_traces = True , show_locals    = False, source_code          = False ,
                ignore        = None , include      = None , show_path      = False, duration_bigger_than = 0     ,
                max_string    = None , show_types   = False, show_duration  = False ,# show_caller    = False     ,         # todo: add back when show_caller is working again
                show_class    = False, contains     = None , show_internals = False, enabled              = True  ,
                extra_data    = False, show_lines   = False, print_lines    = False, show_types_padding   = None  , duration_padding=None):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            config_kwargs = dict(title=title, print_traces_on_exit=print_traces, print_locals=show_locals,
                                 capture_locals = show_locals,
                                 trace_capture_source_code=source_code, ignore_start_with=ignore,
                                 trace_capture_start_with=include, print_max_string_length=max_string,
                                 show_parent_info=show_types, show_method_class=show_class,
                                 show_source_code_path=show_path,
                                 capture_duration=show_duration, print_duration= show_duration,
                                 with_duration_bigger_than=duration_bigger_than,
                                 trace_capture_contains=contains, trace_show_internals=show_internals,
                                 capture_extra_data=extra_data,
                                 print_padding_parent_info= show_types_padding, print_padding_duration=duration_padding,
                                 print_lines_on_exit=print_lines, trace_enabled=enabled,
                                 trace_capture_lines=show_lines or print_lines)

            config = (Trace_Call__Config().update_from_kwargs (**config_kwargs))

            with Trace_Call(config=config):
                result = func(*args, **kwargs)
                return result
        return wrapper
    return decorator

Classes

class Trace_Call (**kwargs)

A mixin class to strictly assign keyword arguments to pre-defined instance attributes during initialization.

This base class provides an init method that assigns values from keyword arguments to instance attributes. If an attribute with the same name as a key from the kwargs is defined in the class, it will be set to the value from kwargs. If the key does not match any predefined attribute names, an exception is raised.

This behavior enforces strict control over the attributes of instances, ensuring that only predefined attributes can be set at the time of instantiation and avoids silent attribute creation which can lead to bugs in the code.

Usage

class MyConfigurableClass(Kwargs_To_Self): attribute1 = 'default_value' attribute2 = True attribute3 : str attribute4 : list attribute4 : int = 42

# Other methods can be added here

Correctly override default values by passing keyword arguments

instance = MyConfigurableClass(attribute1='new_value', attribute2=False)

This will raise an exception as 'attribute3' is not predefined

instance = MyConfigurableClass(attribute3='invalid_attribute')

this will also assign the default value to any variable that has a type defined. In the example above the default values (mapped by default__kwargs and locals) will be: attribute1 = 'default_value' attribute2 = True attribute3 = '' # default value of str attribute4 = [] # default value of list attribute4 = 42 # defined value in the class

Note

It is important that all attributes which may be set at instantiation are predefined in the class. Failure to do so will result in an exception being raised.

Methods

init(**kwargs): The initializer that handles the assignment of keyword arguments to instance attributes. It enforces strict attribute assignment rules, only allowing attributes that are already defined in the class to be set.

Initialize an instance of the derived class, strictly assigning provided keyword arguments to corresponding instance attributes.

Parameters

**kwargs: Variable length keyword arguments.

Raises

Exception
If a key from kwargs does not correspond to any attribute pre-defined in the class, an exception is raised to prevent setting an undefined attribute.
Expand source code
class Trace_Call(Kwargs_To_Self):

    config             : Trace_Call__Config
    started            : bool
    prev_trace_function: None

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.trace_call_handler                                 = Trace_Call__Handler     (config=self.config)
        self.trace_call_print_traces                            = Trace_Call__Print_Traces(config=self.config)
        self.trace_call_view_model                              = Trace_Call__View_Model  ()
        self.config.print_traces_on_exit                        = self.config.print_traces_on_exit
        #self.config.trace_capture_start_with                    = self.config.capture_start_with       or []          # todo add a better way to set these to [] when then value is null
        self.config.trace_ignore_start_with                     = self.config.ignore_start_with        or []          #      probablty better done inside Kwargs_To_Self since it doesn't make sense for lists or dicts to have None value
        self.config.trace_capture_contains                      = self.config.trace_capture_contains   or []          #      and None will be quite common since we can use [] on method's params
        self.config.print_max_string_length                     = self.config.print_max_string_length  or PRINT_MAX_STRING_LENGTH
        self.stack                                              = self.trace_call_handler.stack
        #self.prev_trace_function                                = None                                                # Stores the previous trace function


    def __enter__(self):
        return self.on_enter()

    def __exit__(self, exc_type, exc_val, exc_tb):
        return self.on_exit()

    def on_enter(self):
        if self.config.trace_enabled:
            self.start()  # Start the tracing
        return self

    def on_exit(self):
        if self.config.trace_enabled:
            self.stop()  # Stop the tracing
            if self.config.print_traces_on_exit:
                self.print()
            if self.config.print_lines_on_exit:
                self.print_lines()

    def capture_all(self):
        self.config.trace_capture_all = True
        return self

    def view_data(self):
        return self.trace_call_view_model.create(self.stack)

    def print(self):
        view_model = self.view_data()
        self.trace_call_print_traces.print_traces(view_model)
        #self.print_lines()
        return view_model

    def print_lines(self):
        print()
        view_model = self.view_data()
        print_lines = Trace_Call__Print_Lines(config=self.config, view_model=view_model)
        print_lines.print_lines()

    def start(self):
        self.trace_call_handler.stack.add_node(title=self.trace_call_handler.config.title)
        self.prev_trace_function = sys.gettrace()
        self.started             = True                                                         # set this here so that it does show in the trace
        sys.settrace(self.trace_call_handler.trace_calls)                                       # Set the new trace function


    def stop(self):
        if self.started:
            sys.settrace(self.prev_trace_function)                                              # Restore the previous trace function
            self.stack.empty_stack()
            self.started = False

    def stats(self):
        return self.trace_call_handler.stats

    def stats_data(self):
        return self.trace_call_handler.stats.raw_call_stats

Ancestors

Subclasses

Class variables

var configTrace_Call__Config
var prev_trace_function : None
var started : bool

Methods

def capture_all(self)
Expand source code
def capture_all(self):
    self.config.trace_capture_all = True
    return self
def on_enter(self)
Expand source code
def on_enter(self):
    if self.config.trace_enabled:
        self.start()  # Start the tracing
    return self
def on_exit(self)
Expand source code
def on_exit(self):
    if self.config.trace_enabled:
        self.stop()  # Stop the tracing
        if self.config.print_traces_on_exit:
            self.print()
        if self.config.print_lines_on_exit:
            self.print_lines()
def print(self)
Expand source code
def print(self):
    view_model = self.view_data()
    self.trace_call_print_traces.print_traces(view_model)
    #self.print_lines()
    return view_model
def print_lines(self)
Expand source code
def print_lines(self):
    print()
    view_model = self.view_data()
    print_lines = Trace_Call__Print_Lines(config=self.config, view_model=view_model)
    print_lines.print_lines()
def start(self)
Expand source code
def start(self):
    self.trace_call_handler.stack.add_node(title=self.trace_call_handler.config.title)
    self.prev_trace_function = sys.gettrace()
    self.started             = True                                                         # set this here so that it does show in the trace
    sys.settrace(self.trace_call_handler.trace_calls)                                       # Set the new trace function
def stats(self)
Expand source code
def stats(self):
    return self.trace_call_handler.stats
def stats_data(self)
Expand source code
def stats_data(self):
    return self.trace_call_handler.stats.raw_call_stats
def stop(self)
Expand source code
def stop(self):
    if self.started:
        sys.settrace(self.prev_trace_function)                                              # Restore the previous trace function
        self.stack.empty_stack()
        self.started = False
def view_data(self)
Expand source code
def view_data(self):
    return self.trace_call_view_model.create(self.stack)

Inherited members