Module osbot_utils.helpers.trace.Trace_Call__Stats

Expand source code
from collections import defaultdict, Counter
from copy import copy

from osbot_utils.utils.Dev import pprint

from osbot_utils.base_classes.Kwargs_To_Self import Kwargs_To_Self


class Trace_Call__Stats(Kwargs_To_Self):

    calls          : int
    calls_skipped  : int
    exceptions     : int
    lines          : int
    returns        : int
    unknowns       : int            # to use for extra events that are not being captured
    raw_call_stats : list

    def __repr__(self):
        return str(self.stats())

    def __eq__(self, target):
        if self is target:
            return True
        return self.stats() == target

    def log_frame(self, frame):
        code        = frame.f_code
        func_name   = code.co_name
        module      = frame.f_globals.get("__name__", "")
        self.raw_call_stats.append((module, func_name))
        return self

    def frames_stats__build_tree(self, d, path, function_name):
        parts = path.split('.')
        current_level = d
        for part in parts[:-1]:  # Go up to the second-to-last element
            if part not in current_level:
                current_level[part] = {}
            current_level = current_level[part]
        if parts[-1] not in current_level:
            current_level[parts[-1]] = Counter()
        current_level[parts[-1]][function_name] += 1

    def frames_stats(self):
        processed_frame_stats = self.frames_stats__process_raw_data()
        return self.to_standard_dict(processed_frame_stats)

    def frames_stats__process_raw_data(self):
        tree = defaultdict(dict)
        for module, function_name in self.raw_call_stats:
            self.frames_stats__build_tree(tree, module, function_name)
        return tree


    def to_standard_dict(self, d):
        if isinstance(d, defaultdict):
            d = {k: self.to_standard_dict(v) for k, v in d.items()}
        if isinstance(d, Counter):
            d = dict(d)
        if isinstance(d, dict):
            return {k: self.to_standard_dict(v) for k, v in d.items()}
        return d

    def stats(self):
        stats = copy(self.__locals__())
        del stats['raw_call_stats']
        return stats

    def print(self):
        pprint(self.stats())

Classes

class Trace_Call__Stats (**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__Stats(Kwargs_To_Self):

    calls          : int
    calls_skipped  : int
    exceptions     : int
    lines          : int
    returns        : int
    unknowns       : int            # to use for extra events that are not being captured
    raw_call_stats : list

    def __repr__(self):
        return str(self.stats())

    def __eq__(self, target):
        if self is target:
            return True
        return self.stats() == target

    def log_frame(self, frame):
        code        = frame.f_code
        func_name   = code.co_name
        module      = frame.f_globals.get("__name__", "")
        self.raw_call_stats.append((module, func_name))
        return self

    def frames_stats__build_tree(self, d, path, function_name):
        parts = path.split('.')
        current_level = d
        for part in parts[:-1]:  # Go up to the second-to-last element
            if part not in current_level:
                current_level[part] = {}
            current_level = current_level[part]
        if parts[-1] not in current_level:
            current_level[parts[-1]] = Counter()
        current_level[parts[-1]][function_name] += 1

    def frames_stats(self):
        processed_frame_stats = self.frames_stats__process_raw_data()
        return self.to_standard_dict(processed_frame_stats)

    def frames_stats__process_raw_data(self):
        tree = defaultdict(dict)
        for module, function_name in self.raw_call_stats:
            self.frames_stats__build_tree(tree, module, function_name)
        return tree


    def to_standard_dict(self, d):
        if isinstance(d, defaultdict):
            d = {k: self.to_standard_dict(v) for k, v in d.items()}
        if isinstance(d, Counter):
            d = dict(d)
        if isinstance(d, dict):
            return {k: self.to_standard_dict(v) for k, v in d.items()}
        return d

    def stats(self):
        stats = copy(self.__locals__())
        del stats['raw_call_stats']
        return stats

    def print(self):
        pprint(self.stats())

Ancestors

Class variables

var calls : int
var calls_skipped : int
var exceptions : int
var lines : int
var raw_call_stats : list
var returns : int
var unknowns : int

Methods

def frames_stats(self)
Expand source code
def frames_stats(self):
    processed_frame_stats = self.frames_stats__process_raw_data()
    return self.to_standard_dict(processed_frame_stats)
def frames_stats__build_tree(self, d, path, function_name)
Expand source code
def frames_stats__build_tree(self, d, path, function_name):
    parts = path.split('.')
    current_level = d
    for part in parts[:-1]:  # Go up to the second-to-last element
        if part not in current_level:
            current_level[part] = {}
        current_level = current_level[part]
    if parts[-1] not in current_level:
        current_level[parts[-1]] = Counter()
    current_level[parts[-1]][function_name] += 1
def frames_stats__process_raw_data(self)
Expand source code
def frames_stats__process_raw_data(self):
    tree = defaultdict(dict)
    for module, function_name in self.raw_call_stats:
        self.frames_stats__build_tree(tree, module, function_name)
    return tree
def log_frame(self, frame)
Expand source code
def log_frame(self, frame):
    code        = frame.f_code
    func_name   = code.co_name
    module      = frame.f_globals.get("__name__", "")
    self.raw_call_stats.append((module, func_name))
    return self
def print(self)
Expand source code
def print(self):
    pprint(self.stats())
def stats(self)
Expand source code
def stats(self):
    stats = copy(self.__locals__())
    del stats['raw_call_stats']
    return stats
def to_standard_dict(self, d)
Expand source code
def to_standard_dict(self, d):
    if isinstance(d, defaultdict):
        d = {k: self.to_standard_dict(v) for k, v in d.items()}
    if isinstance(d, Counter):
        d = dict(d)
    if isinstance(d, dict):
        return {k: self.to_standard_dict(v) for k, v in d.items()}
    return d

Inherited members