Reference

hunter.trace(*predicates, **options) Starts tracing.
hunter.stop() Stop tracing.
hunter.wrap([function_to_trace]) Functions decorated with this will be traced.
hunter.And(*predicates, **kwargs) Helper that flattens out predicates in a single hunter.predicates.And object if possible.
hunter.Backlog(*conditions, **kwargs) Helper that merges kwargs and conditions prior to creating the Backlog.
hunter.From([condition, predicate, watermark]) Helper that converts keyword arguments to From(condition=Q(**normal_kwargs), predicate=Q(**rel_kwargs) where rel_kwargs are all the kwargs that start with “depth” or “calls”.
hunter.Not(*predicates, **kwargs) Helper that flattens out predicates in a single hunter.predicates.And object if possible.
hunter.Or(*predicates, **kwargs) Helper that flattens out predicates in a single hunter.predicates.Or object if possible.
hunter.Q(*predicates, **query) Helper that handles situations where hunter.predicates.Query objects (or other callables) are passed in as positional arguments - it conveniently converts those to a hunter.predicates.And predicate.
hunter.actions.CallPrinter(*args, **kwargs) An action that just prints the code being executed, but unlike hunter.CodePrinter it indents based on callstack depth and it also shows repr() of function arguments.
hunter.actions.CodePrinter([stream, …]) An action that just prints the code being executed.
hunter.actions.ColorStreamAction([stream, …]) Baseclass for your custom action.
hunter.actions.Debugger([klass]) An action that starts pdb.
hunter.actions.ErrorSnooper(*args, **kwargs) An action that prints events around silenced exceptions.
hunter.actions.Manhole(**options)
hunter.actions.StackPrinter([depth, limit]) An action that prints a one-line stacktrace.
hunter.actions.VarsPrinter(*names, **options) An action that prints local variables and optionally global variables visible from the current executing frame.
hunter.actions.VarsSnooper(**options) A PySnooper-inspired action, similar to VarsPrinter, but only show variable changes.

Warning

The following (Predicates and Internals) have Cython implementations in modules prefixed with “_”. They should be imported from the hunter module, not hunter.something to be sure you get the best available implementation.

hunter.predicates.And(*predicates) Logical conjunction.
hunter.predicates.Backlog(condition[, size, …]) Until-point buffering mechanism.
hunter.predicates.From(condition[, …]) From-point filtering mechanism.
hunter.predicates.Not(predicate) Logical complement (negation).
hunter.predicates.Or(*predicates) Logical disjunction.
hunter.predicates.Query(**query) Event-filtering predicate.
hunter.predicates.When(condition, *actions) Conditional predicate.
hunter.event.Event(frame, kind, arg[, …]) A wrapper object for Frame objects.
hunter.tracer.Tracer([threading_support, …]) Tracer object.




Helpers

hunter.trace(*predicates, clear_env_var=False, action=CodePrinter, actions=[], **kwargs)[source]

Starts tracing. Can be used as a context manager (with slightly incorrect semantics - it starts tracing before __enter__ is called).

Parameters:

*predicates (callables) – Runs actions if all of the given predicates match.

Keyword Arguments:
 
  • clear_env_var – Disables tracing in subprocess. Default: False.
  • threading_support

    Enable tracing new threads. Default: None.

    Modes:

    • None - automatic (enabled but actions only prefix with thread name if more than 1 thread)
    • False - completely disabled
    • True - enabled (actions always prefix with thread name)

    You can also use: threads_support, thread_support, threadingsupport, threadssupport, threadsupport, threading, threads or thread.

  • action – Action to run if all the predicates return True. Default: CodePrinter.
  • actions – Actions to run (in case you want more than 1).
  • **kwargs – for convenience you can also pass anything that you’d pass to hunter.Q
hunter.stop()[source]

Stop tracing. Restores previous tracer (if there was any).

hunter.wrap(function_to_trace=None, **trace_options)[source]

Functions decorated with this will be traced.

Use local=True to only trace local code, eg:

@hunter.wrap(local=True)
def my_function():
    ...

Keyword arguments are allowed, eg:

@hunter.wrap(action=hunter.CallPrinter)
def my_function():
    ...

Or, filters:

@hunter.wrap(module='foobar')
def my_function():
    ...
hunter.And(*predicates, **kwargs)[source]

Helper that flattens out predicates in a single hunter.predicates.And object if possible. As a convenience it converts kwargs to a single hunter.predicates.Query instance.

Parameters:

Returns: A hunter.predicates.And instance.

hunter.Backlog(*conditions, **kwargs)[source]

Helper that merges kwargs and conditions prior to creating the Backlog.

Parameters:
  • *conditions (callable) – Optional Query object or a callable that returns True/False.
  • size (int) – Number of events that the backlog stores. Effectively this is the maxlen for the internal deque.
  • stack (int) – Stack size to fill. Setting this to 0 disables creating fake call events.
  • vars (bool) – Makes global/local variables available in the stored events. This is an expensive option - it will use action.try_repr on all the variables.
  • strip (bool) – If this option is set then the backlog will be cleared every time an event matching the condition is found. Disabling this may show more context every time an event matching the condition is found but said context may also be duplicated across multiple matches.
  • action (ColorStreamAction) – A ColorStreamAction to display the stored events when an event matching the condition is found.
  • filter (callable) – Optional Query object or a callable that returns True/False to filter the stored events with.
  • **kwargs – Arguments that are passed to hunter.Q(). Any kwarg that starts with “depth” or “calls” will be included predicate.
hunter.From(condition=None, predicate=None, watermark=0, **kwargs)[source]

Helper that converts keyword arguments to From(condition=Q(**normal_kwargs), predicate=Q(**rel_kwargs) where rel_kwargs are all the kwargs that start with “depth” or “calls”.

Parameters:
  • condition (callable) – A callable that returns True/False or a hunter.predicates.Query object.
  • predicate (callable) – Optional callable that returns True/False or a hunter.predicates.Query object to run after condition first returns True.
  • **kwargs – Arguments that are passed to hunter.Q(). Any kwarg that starts with “depth” or “calls” will be included predicate.

Examples

From(function='foobar', depth_lt=5) coverts to From(Q(function='foobar'), Q(depth_lt=5)). The depth filter is moved in the predicate because it would not have any effect as a condition - it stop being called after it returns True, thus it doesn’t have the intended effect (a limit to how deep to trace from foobar).

hunter.Not(*predicates, **kwargs)[source]

Helper that flattens out predicates in a single hunter.predicates.And object if possible. As a convenience it converts kwargs to multiple hunter.predicates.Query instances.

Parameters:

Returns: A hunter.predicates.Not instance (possibly containing a hunter.predicates.And instance).

hunter.Or(*predicates, **kwargs)[source]

Helper that flattens out predicates in a single hunter.predicates.Or object if possible. As a convenience it converts kwargs to multiple hunter.predicates.Query instances.

Parameters:

Returns: A hunter.predicates.Or instance.

hunter.Q(*predicates, **query)[source]

Helper that handles situations where hunter.predicates.Query objects (or other callables) are passed in as positional arguments - it conveniently converts those to a hunter.predicates.And predicate.


Actions

class hunter.actions.CallPrinter(stream=sys.stderr, force_colors=False, force_pid=False, filename_alignment=40, thread_alignment=12, pid_alignment=9, repr_limit=1024, repr_func='safe_repr')[source]

An action that just prints the code being executed, but unlike hunter.CodePrinter it indents based on callstack depth and it also shows repr() of function arguments.

Parameters:
  • stream (file-like) – Stream to write to. Default: sys.stderr.
  • filename_alignment (int) – Default size for the filename column (files are right-aligned). Default: 40.
  • force_colors (bool) – Force coloring. Default: False.
  • repr_limit (bool) – Limit length of repr() output. Default: 512.
  • repr_func (string or callable) – Function to use instead of repr. If string must be one of ‘repr’ or ‘safe_repr’. Default: 'safe_repr'.

New in version 1.2.0.

__call__(event)[source]

Handle event and print filename, line number and source code. If event.kind is a return or exception also prints values.

__init__(*args, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

class hunter.actions.CodePrinter(stream=sys.stderr, force_colors=False, force_pid=False, filename_alignment=40, thread_alignment=12, pid_alignment=9, repr_limit=1024, repr_func='safe_repr')[source]

An action that just prints the code being executed.

Parameters:
  • stream (file-like) – Stream to write to. Default: sys.stderr.
  • filename_alignment (int) – Default size for the filename column (files are right-aligned). Default: 40.
  • force_colors (bool) – Force coloring. Default: False.
  • repr_limit (bool) – Limit length of repr() output. Default: 512.
  • repr_func (string or callable) – Function to use instead of repr. If string must be one of ‘repr’ or ‘safe_repr’. Default: 'safe_repr'.
__call__(event)[source]

Handle event and print filename, line number and source code. If event.kind is a return or exception also prints values.

class hunter.actions.ColorStreamAction(stream=sys.stderr, force_colors=False, force_pid=False, filename_alignment=40, thread_alignment=12, pid_alignment=9, repr_limit=1024, repr_func='safe_repr')[source]

Baseclass for your custom action. Just implement your own __call__.

__eq__(other)[source]

Return self==value.

__init__(stream=None, force_colors=False, force_pid=False, filename_alignment=40, thread_alignment=12, pid_alignment=9, repr_limit=1024, repr_func='safe_repr')[source]

Initialize self. See help(type(self)) for accurate signature.

__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

filename_prefix(event=None)[source]

Get an aligned and trimmed filename prefix for the given event.

Returns: string

output(format_str, *args, **kwargs)[source]

Write format_str.format(*args, **ANSI_COLORS, **kwargs) to self.stream.

For ANSI coloring you can place these in the format_str:

  • {BRIGHT}
  • {DIM}
  • {NORMAL}
  • {RESET}
  • {fore(BLACK)}
  • {fore(RED)}
  • {fore(GREEN)}
  • {fore(YELLOW)}
  • {fore(BLUE)}
  • {fore(MAGENTA)}
  • {fore(CYAN)}
  • {fore(WHITE)}
  • {fore(RESET)}
  • {back(BLACK)}
  • {back(RED)}
  • {back(GREEN)}
  • {back(YELLOW)}
  • {back(BLUE)}
  • {back(MAGENTA)}
  • {back(CYAN)}
  • {back(WHITE)}
  • {back(RESET)}
Parameters:
  • format_str – a PEP-3101 format string
  • *args
  • **kwargs

Returns: string

pid_prefix()[source]

Get an aligned and trimmed pid prefix.

thread_prefix(event)[source]

Get an aligned and trimmed thread prefix for the given event.

try_repr(obj)[source]

Safely call self.repr_func(obj). Failures will have special colored output and output is trimmed according to self.repr_limit.

Returns: string

try_source(event, full=False)[source]

Get a failure-colorized source for the given event.

Return: string

try_str(obj)[source]

Safely call str(obj). Failures will have special colored output and output is trimmed according to self.repr_limit.

Only used when dumping detached events.

Returns: string

class hunter.actions.Debugger(klass=pdb.Pdb, **kwargs)[source]

An action that starts pdb.

__call__(event)[source]

Runs a pdb.set_trace at the matching frame.

__eq__(other)[source]

Return self==value.

__init__(klass=<class 'pdb.Pdb'>, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

class hunter.actions.ErrorSnooper(max_events=50, max_depth=1, stream=sys.stderr, force_colors=False, force_pid=False, filename_alignment=40, thread_alignment=12, pid_alignment=9, repr_limit=1024, repr_func='safe_repr')[source]

An action that prints events around silenced exceptions. Note that it inherits the output of CodePrinter so no fancy call indentation.

Warning

Should be considered experimental. May show lots of false positives especially if you’re tracing lots of clumsy code like:

try:
    stuff = something[key]
except KeyError:
    stuff = "default"
Parameters:
  • max_backlog (int) – Maximum number of events to record and display before the silenced exception is raised. Set to 0 to disable and get a speed boost. Default: 10.
  • max_events (int) – Maximum number of events to record and display for each detected silenced exception. Default: 50.
  • max_depth (int) – Increase if you want to drill into subsequent calls after an exception is raised. If you increase this you might want to also increase max_events since subsequent calls may have so many events you won’t get to see the return event. Default: 0 (doesn’t drill into any calls).
  • stream (file-like) – Stream to write to. Default: sys.stderr.
  • filename_alignment (int) – Default size for the filename column (files are right-aligned). Default: 40.
  • force_colors (bool) – Force coloring. Default: False.
  • repr_limit (bool) – Limit length of repr() output. Default: 512.
  • repr_func (string or callable) – Function to use instead of repr. If string must be one of ‘repr’ or ‘safe_repr’. Default: 'safe_repr'.

New in version 3.1.0.

__call__(event)[source]

Handle event and print filename, line number and source code. If event.kind is a return or exception also prints values.

__init__(*args, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

class hunter.actions.Manhole(**options)[source]
__call__(event)[source]

Call self as a function.

__eq__(other)[source]

Return self==value.

__init__(**options)[source]

Initialize self. See help(type(self)) for accurate signature.

__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

class hunter.actions.StackPrinter(depth=15, limit=2, stream=sys.stderr, force_colors=False, force_pid=False, filename_alignment=40, thread_alignment=12, pid_alignment=9, repr_limit=1024, repr_func='safe_repr')[source]

An action that prints a one-line stacktrace.

Parameters:
  • depth (int) – The maximum number of frames to show.
  • limit (int) – The maximum number of components to show in path. Eg: limit=2 means it will show 1 parent: foo/bar.py.
  • stream (file-like) – Stream to write to. Default: sys.stderr.
  • filename_alignment (int) – Default size for the filename column (files are right-aligned). Default: 40.
  • force_colors (bool) – Force coloring. Default: False.
  • repr_limit (bool) – Limit length of repr() output. Default: 512.
  • repr_func (string or callable) – Function to use instead of repr. If string must be one of ‘repr’ or ‘safe_repr’. Default: 'safe_repr'.
__call__(event)[source]

Handle event and print the stack.

__init__(depth=15, limit=2, **options)[source]

Initialize self. See help(type(self)) for accurate signature.

class hunter.actions.VarsPrinter(name, [name, [name, [..., ]]]stream=sys.stderr, force_colors=False, force_pid=False, filename_alignment=40, thread_alignment=12, pid_alignment=9, repr_limit=1024, repr_func='safe_repr')[source]

An action that prints local variables and optionally global variables visible from the current executing frame.

Parameters:
  • *names (strings) – Names to evaluate. Expressions can be used (will only try to evaluate if all the variables are present on the frame.
  • stream (file-like) – Stream to write to. Default: sys.stderr.
  • filename_alignment (int) – Default size for the filename column (files are right-aligned). Default: 40.
  • force_colors (bool) – Force coloring. Default: False.
  • repr_limit (bool) – Limit length of repr() output. Default: 512.
  • repr_func (string or callable) – Function to use instead of repr. If string must be one of ‘repr’ or ‘safe_repr’. Default: 'safe_repr'.
__call__(event)[source]

Handle event and print the specified variables.

__init__(*names, **options)[source]

Initialize self. See help(type(self)) for accurate signature.

class hunter.actions.VarsSnooper(stream=sys.stderr, force_colors=False, force_pid=False, filename_alignment=40, thread_alignment=12, pid_alignment=9, repr_limit=1024, repr_func='safe_repr')[source]

A PySnooper-inspired action, similar to VarsPrinter, but only show variable changes.

Warning

Should be considered experimental. Use judiciously.

  • It stores reprs for all seen variables, therefore it can use lots of memory.
  • Will leak memory if you filter the return events (eg: ~Q(kind="return")).
  • Not thoroughly tested. May misbehave on code with closures/nonlocal variables.
Parameters:
  • stream (file-like) – Stream to write to. Default: sys.stderr.
  • filename_alignment (int) – Default size for the filename column (files are right-aligned). Default: 40.
  • force_colors (bool) – Force coloring. Default: False.
  • repr_limit (bool) – Limit length of repr() output. Default: 512.
  • repr_func (string or callable) – Function to use instead of repr. If string must be one of ‘repr’ or ‘safe_repr’. Default: 'safe_repr'.
__call__(event)[source]

Handle event and print the specified variables.

__init__(**options)[source]

Initialize self. See help(type(self)) for accurate signature.


Predicates

Warning

These have Cython implementations in modules prefixed with “_”.

Note that:

  • Every predicate except When has a helper importable directly from the hunter package.
  • Ideally you’d use the helpers instead of these to get the best available implementation, extra validation and better argument handling.
class hunter.predicates.And(*predicates)[source]

Logical conjunction. Returns False at the first sub-predicate that returns False, otherwise returns True.

__and__(other)[source]

Convenience API so you can do And(...) & other. It converts that to And(..., other).

__call__(event)[source]

Handles the event.

__eq__(other)[source]

Return self==value.

__init__(*predicates)[source]

Initialize self. See help(type(self)) for accurate signature.

__invert__()[source]

Convenience API so you can do ~And(...). It converts that to Not(And(...)).

__or__(other)[source]

Convenience API so you can do And(...) | other. It converts that to Or(And(...), other).

__rand__(other)[source]

Convenience API so you can do other & And(...). It converts that to And(other, And(...)).

__repr__()[source]

Return repr(self).

__ror__(other)[source]

Convenience API so you can do other | And(...). It converts that to Or(other, And(...)).

__str__()[source]

Return str(self).

__weakref__

list of weak references to the object (if defined)

class hunter.predicates.Backlog(condition, size=100, stack=10, vars=False, strip=True, action=None, filter=None)[source]

Until-point buffering mechanism. It will buffer detached events up to the given size and display them using the given action when condition returns True.

This is a complement to From - essentially working the other way. While From shows events after something interesting occurred the Backlog will show events prior to something interesting occurring.

If the depth delta from the first event in the backlog and the event that matched the condition is less than the given stack then it will create fake call events to be passed to the action before the events from the backlog are passed in.

Using a filter or pre-filtering is recommended to reduce storage work and improve tracing speed. Pre-filtering means that you use Backlog inside a When or :class:`~hunter.And - effectively reducing the number of Events that get to the Backlog.

Parameters:
  • condition (callable) – Optional Query object or a callable that returns True/False.
  • size (int) – Number of events that the backlog stores. Effectively this is the maxlen for the internal deque.
  • stack (int) – Stack size to fill. Setting this to 0 disables creating fake call events.
  • vars (bool) – Makes global/local variables available in the stored events. This is an expensive option - it will use action.try_repr on all the variables.
  • strip (bool) – If this option is set then the backlog will be cleared every time an event matching the condition is found. Disabling this may show more context every time an event matching the condition is found but said context may also be duplicated across multiple matches.
  • action (ColorStreamAction) – A ColorStreamAction to display the stored events when an event matching the condition is found.
  • filter (callable) – Optional Query object or a callable that returns True/False to filter the stored events with.
__and__(other)[source]

Convenience API so you can do Backlog(...) & other. It converts that to And(Backlog(...), other)).

__call__(event)[source]

Handles the event.

__eq__(other)[source]

Return self==value.

__init__(condition, size=100, stack=10, vars=False, strip=True, action=None, filter=None)[source]

Initialize self. See help(type(self)) for accurate signature.

__invert__()[source]

Convenience API so you can do ~Backlog(...). It converts that to Not(Backlog(...)).

__or__(other)[source]

Convenience API so you can do Backlog(...) | other. It converts that to Or(Backlog(...), other).

__rand__(other)[source]

Convenience API so you can do other & Backlog(...). It converts that to And(other, Backlog(...)).

__repr__()[source]

Return repr(self).

__ror__(other)[source]

Convenience API so you can do other | Backlog(...). It converts that to Or(other, Backlog(...)).

__str__()[source]

Return str(self).

__weakref__

list of weak references to the object (if defined)

filter(*predicates, **kwargs)[source]

Returns another Backlog instance with extra output filtering. If the current instance already have filters they will be merged by using an And predicate.

Parameters:
  • *predicates (callables) – Callables that returns True/False or Query objects.
  • **kwargs – Arguments that may be passed to Query.

Returns: A new Backlog instance.

class hunter.predicates.From(condition, predicate=None, watermark=0)[source]

From-point filtering mechanism. Switches on to running the predicate after condition matches, and switches off when the depth goes lower than the initial level.

After condition(event) returns True the event.depth will be saved and calling this object with an event will return predicate(event) until event.depth - watermark is equal to the depth that was saved.

Parameters:
  • condition (callable) – Optional Query object or a callable that returns True/False.
  • predicate (callable) – Optional Query object or a callable that returns True/False to run after condition first returns True. Note that this predicate will be called with a event-copy that has adjusted depth and calls to the initial point where the condition matched. In other words they will be relative.
  • watermark (int) – Depth difference to switch off and wait again on condition.
__and__(other)[source]

Convenience API so you can do From(...) & other. It converts that to And(From(...), other)).

__call__(event)[source]

Handles the event.

__eq__(other)[source]

Return self==value.

__init__(condition, predicate=None, watermark=0)[source]

Initialize self. See help(type(self)) for accurate signature.

__invert__()[source]

Convenience API so you can do ~From(...). It converts that to Not(From(...)).

__or__(other)[source]

Convenience API so you can do From(...) | other. It converts that to Or(From(...), other).

__rand__(other)[source]

Convenience API so you can do other & From(...). It converts that to And(other, From(...)).

__repr__()[source]

Return repr(self).

__ror__(other)[source]

Convenience API so you can do other | From(...). It converts that to Or(other, From(...)).

__str__()[source]

Return str(self).

__weakref__

list of weak references to the object (if defined)

class hunter.predicates.Not(predicate)[source]

Logical complement (negation). Simply returns not predicate(event).

__and__(other)[source]

Convenience API so you can do Not(...) & other. It converts that to And(Not(...), other).

Note that Not(...) & Not(...) converts to Not(Or(..., ...)).

__call__(event)[source]

Handles the event.

__eq__(other)[source]

Return self==value.

__init__(predicate)[source]

Initialize self. See help(type(self)) for accurate signature.

__invert__()[source]

Convenience API so you can do ~Not(...). It converts that to ....

__or__(other)[source]

Convenience API so you can do Not(...) | other. It converts that to Or(Not(...), other).

Note that Not(...) | Not(...) converts to Not(And(..., ...)).

__rand__(other)[source]

Convenience API so you can do other & Not(...). It converts that to And(other, Not(...)).

__repr__()[source]

Return repr(self).

__ror__(other)[source]

Convenience API so you can do other | Not(...). It converts that to Or(other, Not(...)).

__str__()[source]

Return str(self).

__weakref__

list of weak references to the object (if defined)

class hunter.predicates.Or(*predicates)[source]

Logical disjunction. Returns True after the first sub-predicate that returns True.

__and__(other)[source]

Convenience API so you can do Or(...) & other. It converts that to And(Or(...), other).

__call__(event)[source]

Handles the event.

__eq__(other)[source]

Return self==value.

__init__(*predicates)[source]

Initialize self. See help(type(self)) for accurate signature.

__invert__()[source]

Convenience API so you can do ~Or(...). It converts that to Not(Or(...)).

__or__(other)[source]

Convenience API so you can do Or(...) | other. It converts that to Or(..., other).

__rand__(other)[source]

Convenience API so you can do other & Or(...). It converts that to And(other, Or(...)).

__repr__()[source]

Return repr(self).

__ror__(other)[source]

Convenience API so you can do other | Or(...). It converts that to Or(other, Or(...)).

__str__()[source]

Return str(self).

__weakref__

list of weak references to the object (if defined)

class hunter.predicates.Query(**query)[source]

Event-filtering predicate.

See hunter.event.Event for details about the fields that can be filtered on.

Parameters:

query – criteria to match on.

Accepted arguments: arg, builtin, calls, code, depth, filename, frame, fullsource, function, globals, kind, lineno, locals, module, source, stdlib, threadid, threadname.

__and__(other)[source]

Convenience API so you can do Query(...) & Query(...). It converts that to And(Query(...), Query(...)).

__call__(event)[source]

Handles event. Returns True if all criteria matched.

__eq__(other)[source]

Return self==value.

__init__(**query)[source]

Initialize self. See help(type(self)) for accurate signature.

__invert__()[source]

Convenience API so you can do ~Query(...). It converts that to Not(Query(...)).

__or__(other)[source]

Convenience API so you can do Query(...) | Query(...). It converts that to Or(Query(...), Query(...)).

__rand__(other)[source]

Convenience API so you can do other & Query(...). It converts that to And(other, Query(...)).

__repr__()[source]

Return repr(self).

__ror__(other)[source]

Convenience API so you can do other | Query(...). It converts that to Or(other, Query(...)).

__str__()[source]

Return str(self).

__weakref__

list of weak references to the object (if defined)

class hunter.predicates.When(condition, *actions)[source]

Conditional predicate. Runs actions when condition(event) is True.

Actions take a single event argument.

__and__(other)[source]

Convenience API so you can do When(...) & other. It converts that to And(When(...), other).

__call__(event)[source]

Handles the event.

__eq__(other)[source]

Return self==value.

__init__(condition, *actions)[source]

Initialize self. See help(type(self)) for accurate signature.

__invert__()[source]

Convenience API so you can do ~When(...). It converts that to Not(When(...)).

__or__(other)[source]

Convenience API so you can do When(...) | other. It converts that to Or(When(...), other).

__rand__(other)[source]

Convenience API so you can do other & When(...). It converts that to And(other, When(...)).

__repr__()[source]

Return repr(self).

__ror__(other)[source]

Convenience API so you can do other | When(...). It converts that to Or(other, When(...)).

__str__()[source]

Return str(self).

__weakref__

list of weak references to the object (if defined)


Internals

Warning

These have Cython implementations in modules prefixed with “_”. They should be imported from the hunter module, not hunter.something to be sure you get the best available implementation.

Normally these are not used directly. Perhaps just the Tracer may be used directly for performance reasons.

class hunter.event.Event(frame, kind, arg, tracer=None, depth=None, calls=None, threading_support=?)[source]

A wrapper object for Frame objects. Instances of this are passed to your custom functions or predicates.

Provides few convenience properties.

Parameters:
  • frame (Frame) – A python Frame object.
  • kind (str) – A string like 'call', 'line', 'return' or 'exception'.
  • arg – A value that depends on kind. Usually is None but for 'return' or 'exception' other values may be expected.
  • tracer (hunter.tracer.Tracer) – The Tracer instance that created the event. Needed for the calls and depth fields.
__eq__(other)[source]

Return self==value.

__getitem__

Return getattr(self, name).

__init__(frame, kind, arg, tracer=None, depth=None, calls=None, threading_support=?)[source]

Initialize self. See help(type(self)) for accurate signature.

__reduce__()[source]

Helper for pickle.

__repr__()[source]

Return repr(self).

__weakref__

list of weak references to the object (if defined)

arg = None

A value that depends on kind

builtin = None

If kind of the event is one of 'c_call', 'c_return', or 'c_exception' then this will be True.

Type:bool
calls = None

A counter for total number of calls up to this Event.

Type:int
code

A code object (not a string).

depth = None

Tracing depth (increases on calls, decreases on returns).

Type:int
detach(value_filter=None)[source]

Return a copy of the event with references to live objects (like the frame) removed. You should use this if you want to store or use the event outside the handler.

You should use this if you want to avoid memory leaks or side-effects when storing the events.

Parameters:

value_filter – Optional callable that takes one argument: value.

If not specified then the arg, globals and locals fields will be None.

Example usage in a ColorStreamAction subclass:

def __call__(self, event):
    self.events = [event.detach(lambda field, value: self.try_repr(value))]
detached = None

Flag that is True if the event was created with detach().

Type:bool
filename

A string with the path to the module’s file. May be empty if __file__ attribute is missing. May be relative if running scripts.

Type:str
frame = None

The original Frame object.

Note

Not allowed in the builtin predicates (it’s the actual Frame object). You may access it from your custom predicate though.

fullsource

A string with the sourcecode for the current statement (from linecache - failures are ignored).

May include multiple lines if it’s a class/function definition (will include decorators).

Type:str
function

A string with function name.

Type:str
function_object

The function instance.

Warning

Use with prudence.

  • Will be None for decorated functions on Python 2 (methods may still work tho).
  • May be None if tracing functions or classes not defined at module level.
  • May be very slow if tracing modules with lots of variables.
Type:function or None
globals

A dict with global variables.

Type:dict
instruction

Last byte instruction. If no bytecode was used (Cython code) then it returns None. Depending on Python version it might be an int or a single char string.

Type:int or single char string or None
kind = None

The kind of the event, could be one of 'call', 'line', 'return', 'exception'.

Type:str
lineno

An integer with line number in file.

Type:int
locals

A dict with local variables.

Type:dict
module

A string with module name (like 'foo.bar').

Type:str
source

A string with the sourcecode for the current line (from linecache - failures are ignored).

Fast but sometimes incomplete.

Type:str
stdlib

A boolean flag. True if frame is in stdlib.

Type:bool
threadid

Current thread ident. If current thread is main thread then it returns None.

Type:int or None
threading_support = None

A copy of the hunter.tracer.Tracer.threading_support flag.

Note

Not allowed in the builtin predicates. You may access it from your custom predicate though.

Type:bool or None
threadname

Current thread name.

Type:str
class hunter.tracer.Tracer(threading_support=None, profiling_mode=False)[source]

Tracer object.

Parameters:threading_support (bool) – Hooks the tracer into threading.settrace as well if True.
__call__(frame, kind, arg)[source]

The settrace function.

Note

This always returns self (drills down) - as opposed to only drilling down when predicate(event) is True because it might match further inside.

__enter__()[source]

Does nothing. Users are expected to call trace().

Returns: self

__exit__(exc_type, exc_val, exc_tb)[source]

Wrapper around stop(). Does nothing with the arguments.

__init__(threading_support=None, profiling_mode=False)[source]

Initialize self. See help(type(self)) for accurate signature.

__repr__()[source]

Return repr(self).

__weakref__

list of weak references to the object (if defined)

calls = None

A counter for total number of ‘call’ frames that this Tracer went through.

Type:int
depth = None

Tracing depth (increases on calls, decreases on returns)

Type:int
handler

The current predicate. Set via hunter.Tracer.trace().

previous

The previous tracer, if any (whatever sys.gettrace() returned prior to hunter.Tracer.trace()).

profiling_mode = None

True if profiling mode was enabled. Should be considered read-only.

Type:bool
stop()[source]

Stop tracing. Reinstalls the previous tracer.

threading_support = None

True if threading support was enabled. Should be considered read-only.

Type:bool
trace(predicate)[source]

Starts tracing with the given callable.

Parameters:predicate (callable that accepts a single Event argument)
Returns:self