Reference¶
|
Starts tracing. |
Stop tracing. |
|
|
Functions decorated with this will be traced. |
|
Helper that flattens out |
|
Helper that merges kwargs and conditions prior to creating the |
|
Helper that converts keyword arguments to |
|
Helper that flattens out |
|
Helper that flattens out |
|
Helper that handles situations where |
|
An action that just prints the code being executed, but unlike |
|
An action that just prints the code being executed. |
|
Baseclass for your custom action. |
|
An action that starts |
|
An action that prints events around silenced exceptions. |
|
|
|
An action that prints a one-line stacktrace. |
|
An action that prints local variables and optionally global variables visible from the current executing frame. |
|
A PySnooper-inspired action, similar to |
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.
|
Logical conjunction. |
|
Until-point buffering mechanism. |
|
From-point filtering mechanism. |
|
Logical complement (negation). |
|
Logical disjunction. |
|
Event-filtering predicate. |
|
Conditional predicate. |
|
A wrapper object for Frame objects. |
|
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 disabledTrue- enabled (actions always prefix with thread name)
You can also use:
threads_support,thread_support,threadingsupport,threadssupport,threadsupport,threading,threadsorthread.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
See also
- hunter.wrap(function_to_trace=None, **trace_options)[source]¶
Functions decorated with this will be traced.
Use
local=Trueto 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
predicatesin a singlehunter.predicates.Andobject if possible. As a convenience it convertskwargsto a singlehunter.predicates.Queryinstance.- Parameters:
*predicates (callables) – Callables that returns True/False or
hunter.predicates.Queryobjects.**kwargs – Arguments that may be passed to
hunter.predicates.Query.
Returns: A
hunter.predicates.Andinstance.See also
- hunter.Backlog(*conditions, **kwargs)[source]¶
Helper that merges kwargs and conditions prior to creating the
Backlog.- Parameters:
*conditions (callable) – Optional
Queryobject or a callable that returns True/False.size (int) – Number of events that the backlog stores. Effectively this is the
maxlenfor the internal deque.stack (int) – Stack size to fill. Setting this to
0disables 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_repron all the variables.strip (bool) – If this option is set then the backlog will be cleared every time an event matching the
conditionis found. Disabling this may show more context every time an event matching theconditionis 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
conditionis found.filter (callable) – Optional
Queryobject 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.
See also
- 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)whererel_kwargsare all the kwargs that start with “depth” or “calls”.- Parameters:
condition (callable) – A callable that returns True/False or a
hunter.predicates.Queryobject.predicate (callable) – Optional callable that returns True/False or a
hunter.predicates.Queryobject to run afterconditionfirst returnsTrue.**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 toFrom(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 fromfoobar).See also
- hunter.Not(*predicates, **kwargs)[source]¶
Helper that flattens out
predicatesin a singlehunter.predicates.Andobject if possible. As a convenience it convertskwargsto multiplehunter.predicates.Queryinstances.- Parameters:
*predicates (callables) – Callables that returns True/False or
hunter.predicates.Queryobjects.**kwargs – Arguments that may be passed to
hunter.predicates.Query.
Returns: A
hunter.predicates.Notinstance (possibly containing ahunter.predicates.Andinstance).See also
- hunter.Or(*predicates, **kwargs)[source]¶
Helper that flattens out
predicatesin a singlehunter.predicates.Orobject if possible. As a convenience it convertskwargsto multiplehunter.predicates.Queryinstances.- Parameters:
*predicates (callables) – Callables that returns True/False or
hunter.predicates.Queryobjects.**kwargs – Arguments that may be passed to
hunter.predicates.Query.
Returns: A
hunter.predicates.Orinstance.See also
- hunter.Q(*predicates, **query)[source]¶
Helper that handles situations where
hunter.predicates.Queryobjects (or other callables) are passed in as positional arguments - it conveniently converts those to ahunter.predicates.Andpredicate.See also
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.CodePrinterit indents based on callstack depth and it also showsrepr()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'.
Added in version 1.2.0.
- 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'.
- 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__.- __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]¶
- 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)toself.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
- try_repr(obj)[source]¶
Safely call
self.repr_func(obj). Failures will have special colored output and output is trimmed according toself.repr_limit.Returns: string
- 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
CodePrinterso 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_eventssince 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'.
Added in version 3.1.0.
- 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=2means 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'.
- 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'.
- 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'.
Predicates¶
Warning
These have Cython implementations in modules prefixed with “_”.
Note that:
- class hunter.predicates.And(*predicates)[source]¶
Logical conjunction. Returns
Falseat the first sub-predicate that returnsFalse, otherwise returnsTrue.- __and__(other)[source]¶
Convenience API so you can do
And(...) & other. It converts that toAnd(..., other).
- __or__(other)[source]¶
Convenience API so you can do
And(...) | other. It converts that toOr(And(...), other).
- __rand__(other)[source]¶
Convenience API so you can do
other & And(...). It converts that toAnd(other, And(...)).
- __ror__(other)[source]¶
Convenience API so you can do
other | And(...). It converts that toOr(other, And(...)).
- __weakref__¶
list of weak references to the object
- 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
sizeand display them using the givenactionwhenconditionreturns True.This is a complement to
From- essentially working the other way. WhileFromshows 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
stackthen it will create fake call events to be passed to the action before the events from the backlog are passed in.Using a
filteror pre-filtering is recommended to reduce storage work and improve tracing speed. Pre-filtering means that you use Backlog inside aWhenor :class:`~hunter.And - effectively reducing the number of Events that get to the Backlog.- Parameters:
condition (callable) – Optional
Queryobject or a callable that returns True/False.size (int) – Number of events that the backlog stores. Effectively this is the
maxlenfor the internal deque.stack (int) – Stack size to fill. Setting this to
0disables 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_repron all the variables.strip (bool) – If this option is set then the backlog will be cleared every time an event matching the
conditionis found. Disabling this may show more context every time an event matching theconditionis 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
conditionis found.filter (callable) – Optional
Queryobject or a callable that returns True/False to filter the stored events with.
See also
- __and__(other)[source]¶
Convenience API so you can do
Backlog(...) & other. It converts that toAnd(Backlog(...), other)).
- __invert__()[source]¶
Convenience API so you can do
~Backlog(...). It converts that toNot(Backlog(...)).
- __or__(other)[source]¶
Convenience API so you can do
Backlog(...) | other. It converts that toOr(Backlog(...), other).
- __rand__(other)[source]¶
Convenience API so you can do
other & Backlog(...). It converts that toAnd(other, Backlog(...)).
- __ror__(other)[source]¶
Convenience API so you can do
other | Backlog(...). It converts that toOr(other, Backlog(...)).
- __weakref__¶
list of weak references to the object
- 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)returnsTruetheevent.depthwill be saved and calling this object with aneventwill returnpredicate(event)untilevent.depth - watermarkis equal to the depth that was saved.- Parameters:
condition (callable) – Optional
Queryobject or a callable that returns True/False.predicate (callable) – Optional
Queryobject or a callable that returns True/False to run afterconditionfirst returnsTrue. Note that this predicate will be called with a event-copy that has adjusteddepthandcallsto the initial point where theconditionmatched. In other words they will be relative.watermark (int) – Depth difference to switch off and wait again on
condition.
See also
- __and__(other)[source]¶
Convenience API so you can do
From(...) & other. It converts that toAnd(From(...), other)).
- __or__(other)[source]¶
Convenience API so you can do
From(...) | other. It converts that toOr(From(...), other).
- __rand__(other)[source]¶
Convenience API so you can do
other & From(...). It converts that toAnd(other, From(...)).
- __ror__(other)[source]¶
Convenience API so you can do
other | From(...). It converts that toOr(other, From(...)).
- __weakref__¶
list of weak references to the object
- 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 toAnd(Not(...), other).Note that
Not(...) & Not(...)converts toNot(Or(..., ...)).
- __or__(other)[source]¶
Convenience API so you can do
Not(...) | other. It converts that toOr(Not(...), other).Note that
Not(...) | Not(...)converts toNot(And(..., ...)).
- __rand__(other)[source]¶
Convenience API so you can do
other & Not(...). It converts that toAnd(other, Not(...)).
- __ror__(other)[source]¶
Convenience API so you can do
other | Not(...). It converts that toOr(other, Not(...)).
- __weakref__¶
list of weak references to the object
- class hunter.predicates.Or(*predicates)[source]¶
Logical disjunction. Returns
Trueafter the first sub-predicate that returnsTrue.- __and__(other)[source]¶
Convenience API so you can do
Or(...) & other. It converts that toAnd(Or(...), other).
- __or__(other)[source]¶
Convenience API so you can do
Or(...) | other. It converts that toOr(..., other).
- __rand__(other)[source]¶
Convenience API so you can do
other & Or(...). It converts that toAnd(other, Or(...)).
- __ror__(other)[source]¶
Convenience API so you can do
other | Or(...). It converts that toOr(other, Or(...)).
- __weakref__¶
list of weak references to the object
- class hunter.predicates.Query(**query)[source]¶
Event-filtering predicate.
See
hunter.event.Eventfor 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 toAnd(Query(...), Query(...)).
- __invert__()[source]¶
Convenience API so you can do
~Query(...). It converts that toNot(Query(...)).
- __or__(other)[source]¶
Convenience API so you can do
Query(...) | Query(...). It converts that toOr(Query(...), Query(...)).
- __rand__(other)[source]¶
Convenience API so you can do
other & Query(...). It converts that toAnd(other, Query(...)).
- __ror__(other)[source]¶
Convenience API so you can do
other | Query(...). It converts that toOr(other, Query(...)).
- __weakref__¶
list of weak references to the object
- class hunter.predicates.When(condition, *actions)[source]¶
Conditional predicate. Runs
actionswhencondition(event)isTrue.Actions take a single
eventargument.- __and__(other)[source]¶
Convenience API so you can do
When(...) & other. It converts that toAnd(When(...), other).
- __or__(other)[source]¶
Convenience API so you can do
When(...) | other. It converts that toOr(When(...), other).
- __rand__(other)[source]¶
Convenience API so you can do
other & When(...). It converts that toAnd(other, When(...)).
- __ror__(other)[source]¶
Convenience API so you can do
other | When(...). It converts that toOr(other, When(...)).
- __weakref__¶
list of weak references to the object
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 isNonebut for'return'or'exception'other values may be expected.tracer (
hunter.tracer.Tracer) – TheTracerinstance that created the event. Needed for thecallsanddepthfields.
- __getitem__(name, /)¶
Return getattr(self, name).
- __weakref__¶
list of weak references to the object
- 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,globalsandlocalsfields will beNone.
Example usage in a
ColorStreamActionsubclass:def __call__(self, event): self.events = [event.detach(lambda field, value: self.try_repr(value))]
- 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
Nonefor decorated functions on Python 2 (methods may still work tho).May be
Noneif 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.
Trueif 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_supportflag.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.settraceas 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.
- __exit__(exc_type, exc_val, exc_tb)[source]¶
Wrapper around
stop(). Does nothing with the arguments.
- __weakref__¶
list of weak references to the object
- 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 tohunter.Tracer.trace()).
- profiling_mode¶
True if profiling mode was enabled. Should be considered read-only.
- Type:
bool
- threading_support¶
True if threading support was enabled. Should be considered read-only.
- Type:
bool