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.From([predicate, condition, watermark]) Helper that converts keyword arguments to a From(Q(**kwargs)).
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.Manhole(**options)
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 “_”. Should be imported from the hunter module, not hunter.something to be sure you get the right implementation.

hunter.predicates.Query(**query) A query class.
hunter.predicates.From(condition[, …]) From-point filtering mechanism.
hunter.predicates.When(condition, *actions) Runs actions when condition(event) is True.
hunter.predicates.And(*predicates) Returns False at the first sub-predicate that returns False, otherwise returns True.
hunter.predicates.Not(predicate) Simply returns not predicate(event).
hunter.predicates.Or(*predicates) Returns True after the first sub-predicate that returns True.
hunter.predicates.Query(**query) A query class.
hunter.event.Event(frame, kind, arg, tracer) 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.From(predicate=None, condition=None, watermark=0, **kwargs)[source]

Helper that converts keyword arguments to a From(Q(**kwargs)).

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.
  • watermark (int) – Depth difference to switch off and wait again on condition.
  • **kwargs – Arguments that are passed to hunter.Q()
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.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]

x.__eq__(y) <==> x==y

__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]

x.__init__(…) initializes x; see help(type(x)) for signature

__repr__() <==> repr(x)[source]
__str__() <==> str(x)[source]
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

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]

x.__init__(…) initializes x; see help(type(x)) for 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.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]

x.__eq__(y) <==> x==y

__init__(klass=<function <lambda>>, **kwargs)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

__repr__() <==> repr(x)[source]
__str__() <==> str(x)[source]
class hunter.actions.Manhole(**options)[source]
__call__(...) <==> x(...)[source]
__eq__(other)[source]

x.__eq__(y) <==> x==y

__init__(**options)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

__repr__() <==> repr(x)[source]
__str__() <==> str(x)[source]
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]

x.__init__(…) initializes x; see help(type(x)) for 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.

__call__(event)[source]

Handle event and print the specified variables.

__init__(**options)[source]

x.__init__(…) initializes x; see help(type(x)) for signature


Predicates

Warning

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

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

A query class.

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

__call__(event)[source]

Handles event. Returns True if all criteria matched.

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

Runs actions when condition(event) is True.

Actions take a single event argument.

__call__(event)[source]

Handles the event.

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

From-point filtering mechanism. Switches on to running the predicate after condition maches, and switches off when the depth returns to the same 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) – 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.
  • watermark (int) – Depth difference to switch off and wait again on condition.
__call__(event)[source]

Handles the event.

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

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

__call__(event)[source]

Handles the event.

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

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

__call__(event)[source]

Handles the event.

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

Simply returns not predicate(event).

__call__(event)[source]

Handles the event.


Internals

Warning

These have Cython implementations in modules prefixed with “_”. Should be imported from the hunter module, not hunter.something to be sure you get the right 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)[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]

x.__eq__(y) <==> x==y

__getitem__

x.__getattribute__(‘name’) <==> x.name

__init__(frame, kind, arg, tracer)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

__weakref__

list of weak references to the object (if defined)

arg = None

A value that depends on kind

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
kind = None

The kind of the event, could be one of 'call', 'line', 'return', 'exception', 'c_call', 'c_return', or 'c_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)[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.

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()).

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