41. track — track.py

Functions for creating classes with access tracking facilities. This can e.g. be use to detect if the contents of a list or dict has been changed.

41.1. Variables defined in module track

track.track_methods = ['__setitem__', '__setslice__', '__delitem__', 'update', 'append', 'extend', 'add', 'insert', 'pop', 'popitem', 'remove', 'setdefault', '__iadd__']

List of names of methods that can possibly change an object of type dict or list.

41.2. Classes defined in module track

class track.TrackedDict

Tracked dict class

class track.TrackedList(iterable=(), /)

Tracked list class

41.3. Functions defined in module track

track.track_decorator(func)[source]

Create a wrapper function for tracked class methods.

The wrapper function increases the ‘hits’ attribute of the class and then executes the wrapped method. Note that the class is passed as the first argument.

track.track_class_factory(cls, name='', methods=['__setitem__', '__setslice__', '__delitem__', 'update', 'append', 'extend', 'add', 'insert', 'pop', 'popitem', 'remove', 'setdefault', '__iadd__'])[source]

Create a wrapper class with method tracking facilities.

Tracking a class counts the number of times any of the specified class methods has been used. Given an input class, this will return a class with tracking facilities. The tracking occurs on all the specified methods. The default will

Parameters
  • cls (class) – The class to be tracked.

  • name (str, optional) – The name of the class wrapper. If not provided, the name will be ‘Tracked’ followed by the capitalized class name.

  • methods (list of str) – List of class method names that should be taken into account in the tracking. Calls to any of these methods will increment the number of hits. The methods should be owned by the class itself, not by a parent class. The default list will track all methods which could possibly change a ‘list’ or a ‘dict’.

Returns

class – A class wrapping the input class and tracking access to any of the specified methods. The class has an extra attribute ‘hits’ counting the number accesses to one of these methods. This value can be reset to zero to track changes after some breakpoint.

Examples

>>> TrackedDict = track_class_factory(dict)
>>> D = TrackedDict({'a':1,'b':2})
>>> print(D.hits)
0
>>> D['c'] = 3
>>> print(D.hits)
1
>>> D.hits = 0
>>> print(D.hits)
0
>>> D.update({'d':1,'b':3})
>>> del D['a']
>>> print(D.hits)
2