Reference - Hunter 0.1.dev50 documentation (original) (raw)

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:

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:

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:

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 ahunter.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:

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

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:

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

__hash__ = None

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

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

Parameters:

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.

__hash__ = None

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

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

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

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

__call__(event)[source]

Call self as a function.

__eq__(other)[source]

Return self==value.

__hash__ = None

__init__(**options)[source]

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

__call__(event)[source]

Handle event and print the stack.

__init__(depth=15, limit=2, **options)[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:

__call__(event)[source]

Handle event and print the specified variables.

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

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

Warning

Should be considered experimental. Use judiciously.

Parameters:

Handle event and print the specified variables.


Predicates

Warning

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

Note that:

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.

__hash__ = None

__init__(*predicates)[source]

__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 Fromshows 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:

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

__hash__ = None

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

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

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 anevent will return predicate(event) until event.depth - watermark is equal to the depth that was saved.

Parameters:

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

__hash__ = None

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

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

__hash__ = None

__init__(predicate)[source]

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

__hash__ = None

__init__(*predicates)[source]

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

__hash__ = None

__init__(**query)[source]

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

__hash__ = None

__init__(condition, *actions)[source]

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

__eq__(other)[source]

Return self==value.

__getitem__(name, /)

Return getattr(self, name).

__hash__ = None

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

__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

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.

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

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]

__repr__()[source]

Return repr(self).

__weakref__

list of weak references to the object (if defined)

calls

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

Type:

int

depth

Tracing depth (increases on calls, decreases on returns)

Type:

int

property handler

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

property previous

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

profiling_mode

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

Type:

bool

stop()[source]

Stop tracing. Reinstalls the previous tracer.

threading_support

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