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 ([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.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 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 disabledTrue
- enabled (actions always prefix with thread name)
You can also use:
threads_support
,thread_support
,threadingsupport
,threadssupport
,threadsupport
,threading
,threads
orthread
. - 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
- clear_env_var – Disables tracing in subprocess. Default:
-
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 singlehunter.predicates.And
object if possible. As a convenience it convertskwargs
to a singlehunter.predicates.Query
instance.Parameters: - *predicates (callables) – Callables that returns True/False or
hunter.predicates.Query
objects. - **kwargs – Arguments that may be passed to
hunter.predicates.Query
Returns: A
hunter.predicates.And
instance.See also
- *predicates (callables) – Callables that returns True/False or
-
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_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 aftercondition
first 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
- condition (callable) – A callable that returns True/False or a
-
hunter.
Not
(*predicates, **kwargs)[source]¶ Helper that flattens out
predicates
in a singlehunter.predicates.And
object if possible. As a convenience it convertskwargs
to multiplehunter.predicates.Query
instances.Parameters: - *predicates (callables) – Callables that returns True/False or
hunter.predicates.Query
objects. - **kwargs – Arguments that may be passed to
hunter.predicates.Query
.
Returns: A
hunter.predicates.Not
instance (possibly containing ahunter.predicates.And
instance).See also
- *predicates (callables) – Callables that returns True/False or
-
hunter.
Or
(*predicates, **kwargs)[source]¶ Helper that flattens out
predicates
in a singlehunter.predicates.Or
object if possible. As a convenience it convertskwargs
to multiplehunter.predicates.Query
instances.Parameters: - *predicates (callables) – Callables that returns True/False or
hunter.predicates.Query
objects. - **kwargs – Arguments that may be passed to
hunter.predicates.Query
.
Returns: A
hunter.predicates.Or
instance.See also
- *predicates (callables) – Callables that returns True/False or
-
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.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.CodePrinter
it 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'
.
New in version 1.2.0.
- stream (file-like) – Stream to write to. Default:
-
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'
.
- stream (file-like) – Stream to write to. Default:
-
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]¶ x.__init__(…) initializes x; see help(type(x)) for signature
-
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.
Debugger
(klass=pdb.Pdb, **kwargs)[source]¶ An action that starts
pdb
.
-
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.
- 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:
-
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 “_”.
They 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.-
__and__
(other)[source]¶ Convenience API so you can do
Query(...) & Query(...)
. It converts that toAnd(Query(...), Query(...))
.
-
__init__
(**query)[source]¶ Parameters: query – criteria to match on.
Accepted arguments:
arg
,calls
,code
,depth
,filename
,frame
,fullsource
,function
,globals
,kind
,lineno
,locals
,module
,source
,stdlib
,threadid
,threadname
.
-
__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 (if defined)
-
-
class
hunter.predicates.
When
(condition, *actions)[source]¶ Runs
actions
whencondition(event)
isTrue
.Actions take a single
event
argument.-
__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 (if defined)
-
-
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)
returnsTrue
theevent.depth
will be saved and calling this object with anevent
will returnpredicate(event)
untilevent.depth - watermark
is equal to the depth that was saved.Parameters: - condition (callable) – A callable that returns True/False or a
Query
object. - predicate (callable) – Optional callable that returns True/False or a
Query
object to run aftercondition
first returnsTrue
. Note that this predicate will be called with a event-copy that has adjusteddepth
andcalls
to the initial point where thecondition
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 toAnd(From(...), other))
.
-
__init__
(condition, predicate=None, watermark=0)[source]¶ x.__init__(…) initializes x; see help(type(x)) for signature
-
__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 (if defined)
- condition (callable) – A callable that returns True/False or a
-
class
hunter.predicates.
And
(*predicates)[source]¶ Returns
False
at 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 (if defined)
-
-
class
hunter.predicates.
Or
(*predicates)[source]¶ Returns
True
after 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 (if defined)
-
-
class
hunter.predicates.
Not
(predicate)[source]¶ 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 (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 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 isNone
but for'return'
or'exception'
other values may be expected. - tracer (
hunter.tracer.Tracer
) – TheTracer
instance that created the event. Needed for thecalls
anddepth
fields.
-
__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
andlocals
fields will beNone
.Example usage in a
ColorStreamAction
subclass: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
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 - Will be
-
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.
-
__exit__
(exc_type, exc_val, exc_tb)[source]¶ Wrapper around
stop()
. Does nothing with the arguments.
-
__init__
(threading_support=None)[source]¶ x.__init__(…) initializes x; see help(type(x)) for signature
-
__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 tohunter.Tracer.trace()
).
-
threading_support
= None¶ True if threading support was enabled. Should be considered read-only.
Type: bool
-