Contents

Overview

docs Documentation Status
tests
Travis-CI Build Status AppVeyor Build Status Requirements Status
Coverage Status
package
PyPI Package latest release PyPI Wheel Supported versions Supported implementations
Commits since latest release

Hunter is a flexible code tracing toolkit, not for measuring coverage, but for debugging, logging, inspection and other nefarious purposes. It has a simple Python API, a convenient terminal API and a CLI tool to attach to processes.

  • Free software: BSD 2-Clause License

Installation

pip install hunter

Overview

Basic use involves passing various filters to the trace option. An example:

import hunter
hunter.trace(module='posixpath', action=hunter.CallPrinter)

import os
os.path.join('a', 'b')

That would result in:

>>> os.path.join('a', 'b')
         /usr/lib/python3.6/posixpath.py:75    call      => join(a='a')
         /usr/lib/python3.6/posixpath.py:80    line         a = os.fspath(a)
         /usr/lib/python3.6/posixpath.py:81    line         sep = _get_sep(a)
         /usr/lib/python3.6/posixpath.py:41    call         => _get_sep(path='a')
         /usr/lib/python3.6/posixpath.py:42    line            if isinstance(path, bytes):
         /usr/lib/python3.6/posixpath.py:45    line            return '/'
         /usr/lib/python3.6/posixpath.py:45    return       <= _get_sep: '/'
         /usr/lib/python3.6/posixpath.py:82    line         path = a
         /usr/lib/python3.6/posixpath.py:83    line         try:
         /usr/lib/python3.6/posixpath.py:84    line         if not p:
         /usr/lib/python3.6/posixpath.py:86    line         for b in map(os.fspath, p):
         /usr/lib/python3.6/posixpath.py:87    line         if b.startswith(sep):
         /usr/lib/python3.6/posixpath.py:89    line         elif not path or path.endswith(sep):
         /usr/lib/python3.6/posixpath.py:92    line         path += sep + b
         /usr/lib/python3.6/posixpath.py:86    line         for b in map(os.fspath, p):
         /usr/lib/python3.6/posixpath.py:96    line         return path
         /usr/lib/python3.6/posixpath.py:96    return    <= join: 'a/b'
'a/b'

In a terminal it would look like:

https://raw.githubusercontent.com/ionelmc/python-hunter/master/docs/code-trace.png

Actions

Output format can be controlled with “actions”. There’s an alternative CodePrinter action that doesn’t handle nesting (it was the default action until Hunter 2.0).

If filters match then action will be run. Example:

import hunter
hunter.trace(module='posixpath', action=hunter.CodePrinter)

import os
os.path.join('a', 'b')

That would result in:

>>> os.path.join('a', 'b')
         /usr/lib/python3.6/posixpath.py:75    call      def join(a, *p):
         /usr/lib/python3.6/posixpath.py:80    line          a = os.fspath(a)
         /usr/lib/python3.6/posixpath.py:81    line          sep = _get_sep(a)
         /usr/lib/python3.6/posixpath.py:41    call      def _get_sep(path):
         /usr/lib/python3.6/posixpath.py:42    line          if isinstance(path, bytes):
         /usr/lib/python3.6/posixpath.py:45    line              return '/'
         /usr/lib/python3.6/posixpath.py:45    return            return '/'
                                               ...       return value: '/'
         /usr/lib/python3.6/posixpath.py:82    line          path = a
         /usr/lib/python3.6/posixpath.py:83    line          try:
         /usr/lib/python3.6/posixpath.py:84    line              if not p:
         /usr/lib/python3.6/posixpath.py:86    line              for b in map(os.fspath, p):
         /usr/lib/python3.6/posixpath.py:87    line                  if b.startswith(sep):
         /usr/lib/python3.6/posixpath.py:89    line                  elif not path or path.endswith(sep):
         /usr/lib/python3.6/posixpath.py:92    line                      path += sep + b
         /usr/lib/python3.6/posixpath.py:86    line              for b in map(os.fspath, p):
         /usr/lib/python3.6/posixpath.py:96    line          return path
         /usr/lib/python3.6/posixpath.py:96    return        return path
                                               ...       return value: 'a/b'
'a/b'
  • or in a terminal:
https://raw.githubusercontent.com/ionelmc/python-hunter/master/docs/simple-trace.png

Another useful action is the VarsPrinter:

import hunter
# note that this kind of invocation will also use the default `CallPrinter` action
hunter.trace(hunter.Q(module='posixpath', action=hunter.VarsPrinter('path')))

import os
os.path.join('a', 'b')

That would result in:

>>> os.path.join('a', 'b')
     /usr/lib/python3.6/posixpath.py:75    call      => join(a='a')
     /usr/lib/python3.6/posixpath.py:80    line         a = os.fspath(a)
     /usr/lib/python3.6/posixpath.py:81    line         sep = _get_sep(a)
     /usr/lib/python3.6/posixpath.py:41    call      [path => 'a']
     /usr/lib/python3.6/posixpath.py:41    call         => _get_sep(path='a')
     /usr/lib/python3.6/posixpath.py:42    line      [path => 'a']
     /usr/lib/python3.6/posixpath.py:42    line            if isinstance(path, bytes):
     /usr/lib/python3.6/posixpath.py:45    line      [path => 'a']
     /usr/lib/python3.6/posixpath.py:45    line            return '/'
     /usr/lib/python3.6/posixpath.py:45    return    [path => 'a']
     /usr/lib/python3.6/posixpath.py:45    return       <= _get_sep: '/'
     /usr/lib/python3.6/posixpath.py:82    line         path = a
     /usr/lib/python3.6/posixpath.py:83    line      [path => 'a']
     /usr/lib/python3.6/posixpath.py:83    line         try:
     /usr/lib/python3.6/posixpath.py:84    line      [path => 'a']
     /usr/lib/python3.6/posixpath.py:84    line         if not p:
     /usr/lib/python3.6/posixpath.py:86    line      [path => 'a']
     /usr/lib/python3.6/posixpath.py:86    line         for b in map(os.fspath, p):
     /usr/lib/python3.6/posixpath.py:87    line      [path => 'a']
     /usr/lib/python3.6/posixpath.py:87    line         if b.startswith(sep):
     /usr/lib/python3.6/posixpath.py:89    line      [path => 'a']
     /usr/lib/python3.6/posixpath.py:89    line         elif not path or path.endswith(sep):
     /usr/lib/python3.6/posixpath.py:92    line      [path => 'a']
     /usr/lib/python3.6/posixpath.py:92    line         path += sep + b
     /usr/lib/python3.6/posixpath.py:86    line      [path => 'a/b']
     /usr/lib/python3.6/posixpath.py:86    line         for b in map(os.fspath, p):
     /usr/lib/python3.6/posixpath.py:96    line      [path => 'a/b']
     /usr/lib/python3.6/posixpath.py:96    line         return path
     /usr/lib/python3.6/posixpath.py:96    return    [path => 'a/b']
     /usr/lib/python3.6/posixpath.py:96    return    <= join: 'a/b'
'a/b'

In a terminal it would look like:

https://raw.githubusercontent.com/ionelmc/python-hunter/master/docs/vars-trace.png

You can give it a tree-like configuration where you can optionally configure specific actions for parts of the tree (like dumping variables or a pdb set_trace):

from hunter import trace, Q, Debugger
from pdb import Pdb

trace(
    # drop into a Pdb session if ``foo.bar()`` is called
    Q(module="foo", function="bar", kind="call", action=Debugger(klass=Pdb))
    |  # or
    Q(
        # show code that contains "mumbo.jumbo" on the current line
        lambda event: event.locals.get("mumbo") == "jumbo",
        # and it's not in Python's stdlib
        stdlib=False,
        # and it contains "mumbo" on the current line
        source__contains="mumbo"
    )
)

import foo
foo.func()

With a foo.py like this:

def bar():
    execution_will_get_stopped  # cause we get a Pdb session here

def func():
    mumbo = 1
    mumbo = "jumbo"
    print("not shown in trace")
    print(mumbo)
    mumbo = 2
    print(mumbo) # not shown in trace
    bar()

We get:

>>> foo.func()
not shown in trace
    /home/ionel/osp/python-hunter/foo.py:8     line          print(mumbo)
jumbo
    /home/ionel/osp/python-hunter/foo.py:9     line          mumbo = 2
2
    /home/ionel/osp/python-hunter/foo.py:1     call      def bar():
> /home/ionel/osp/python-hunter/foo.py(2)bar()
-> execution_will_get_stopped  # cause we get a Pdb session here
(Pdb)

In a terminal it would look like:

https://raw.githubusercontent.com/ionelmc/python-hunter/master/docs/tree-trace.png

Tracing processes

In similar fashion to strace Hunter can trace other processes, eg:

hunter-trace --gdb -p 123

If you wanna play it safe (no messy GDB) then add this in your code:

from hunter import remote
remote.install()

Then you can do:

hunter-trace -p 123

See docs on the remote feature.

Note: Windows ain’t supported.

Environment variable activation

For your convenience environment variable activation is available. Just run your app like this:

PYTHONHUNTER="module='os.path'" python yourapp.py

On Windows you’d do something like:

set PYTHONHUNTER=module='os.path'
python yourapp.py

The activation works with a clever .pth file that checks for that env var presence and before your app runs does something like this:

from hunter import *
trace(<whatever-you-had-in-the-PYTHONHUNTER-env-var>)

Note that Hunter is activated even if the env var is empty, eg: PYTHONHUNTER="".

Environment variable configuration

Sometimes you always use the same options (like stdlib=False or force_colors=True). To save typing you can set something like this in your environment:

PYTHONHUNTERCONFIG="stdlib=False,force_colors=True"

This is the same as PYTHONHUNTER="stdlib=False,action=CallPrinter(force_colors=True)".

Notes:

  • Setting PYTHONHUNTERCONFIG alone doesn’t activate hunter.

  • All the options for the builtin actions are supported.

  • Although using predicates is supported it can be problematic. Example of setup that won’t trace anything:

    PYTHONHUNTERCONFIG="Q(module_startswith='django')"
    PYTHONHUNTER="Q(module_startswith='celery')"
    

    which is the equivalent of:

    PYTHONHUNTER="Q(module_startswith='django'),Q(module_startswith='celery')"
    

    which is the equivalent of:

    PYTHONHUNTER="Q(module_startswith='django')&Q(module_startswith='celery')"
    

Filtering DSL

Hunter supports a flexible query DSL, see the introduction.

Development

To run the all tests run:

tox

FAQ

Why not Smiley?

There’s some obvious overlap with smiley but there are few fundamental differences:

  • Complexity. Smiley is simply over-engineered:

    • It uses IPC and a SQL database.
    • It has a webserver. Lots of dependencies.
    • It uses threads. Side-effects and subtle bugs are introduced in your code.
    • It records everything. Tries to dump any variable. Often fails and stops working.

    Why do you need all that just to debug some stuff in a terminal? Simply put, it’s a nice idea but the design choices work against you when you’re already neck-deep into debugging your own code. In my experience Smiley has been very buggy and unreliable. Your mileage may vary of course.

  • Tracing long running code. This will make Smiley record lots of data, making it unusable.

    Now because Smiley records everything, you’d think it’s better suited for short programs. But alas, if your program runs quickly then it’s pointless to record the execution. You can just run it again.

    It seems there’s only one situation where it’s reasonable to use Smiley: tracing io-bound apps remotely. Those apps don’t execute lots of code, they just wait on network so Smiley’s storage won’t blow out of proportion and tracing overhead might be acceptable.

  • Use-cases. It seems to me Smiley’s purpose is not really debugging code, but more of a “non interactive monitoring” tool.

In contrast, Hunter is very simple:

  • Few dependencies.

  • Low overhead (tracing/filtering code has an optional Cython extension).

  • No storage. This simplifies lots of things.

    The only cost is that you might need to run the code multiple times to get the filtering/actions right. This means Hunter is not really suited for “post-mortem” debugging. If you can’t reproduce the problem anymore then Hunter won’t be of much help.

Why not pytrace?

Pytrace is another tracer tool. It seems quite similar to Smiley - it uses a sqlite database for the events, threads and IPC.

TODO: Expand this.

Why (not) coverage?

For purposes of debugging coverage is a great tool but only as far as “debugging by looking at what code is (not) run”. Checking branch coverage is good but it will only get you as far.

From the other perspective, you’d be wondering if you could use Hunter to measure coverage-like things. You could do it but for that purpose Hunter is very “rough”: it has no builtin storage. You’d have to implement your own storage. You can do it but it wouldn’t give you any advantage over making your own tracer if you don’t need to “pre-filter” whatever you’re recording.

In other words, filtering events is the main selling point of Hunter - it’s fast (cython implementation) and the query API is flexible enough.

Installation

At the command line:

pip install hunter

Introduction

Installation

To install hunter run:

pip install hunter

The trace function

The hunter.trace function can take 2 types of arguments:

Note that hunter.trace will use hunter.Q when you pass multiple positional arguments or keyword arguments.

The Q function

The hunter.Q() function provides a convenience API for you:

  • Q(module='foobar') is converted to Query(module='foobar').
  • Q(module='foobar', action=Debugger) is converted to When(Query(module='foobar'), Debugger).
  • Q(module='foobar', actions=[CodePrinter, VarsPrinter('name')]) is converted to When(Query(module='foobar'), CodePrinter, VarsPrinter('name')).
  • Q(Q(module='foo'), Q(module='bar')) is converted to And(Q(module='foo'), Q(module='bar')).
  • Q(your_own_callback, module='foo') is converted to And(your_own_callback, Q(module='foo')).

Note that the default junction hunter.Q() uses is hunter.predicates.And.

Composing

All the builtin predicates (hunter.predicates.Query, hunter.predicates.When, hunter.predicates.And, hunter.predicates.Not and hunter.predicates.Or) support the |, & and ~ operators:

  • Query(module='foo') | Query(module='bar') is converted to Or(Query(module='foo'), Query(module='bar'))
  • Query(module='foo') & Query(module='bar') is converted to And(Query(module='foo'), Query(module='bar'))
  • ~Query(module='foo') is converted to Not(Query(module='foo'))

Operators

New in version 1.0.0: You can add startswith, endswith, in, contains, regex, lt, lte, gt, gte to your keyword arguments, just like in Django. Double underscores are not necessary, but in case you got twitchy fingers it’ll just work - filename__startswith is the same as filename_startswith.

New in version 2.0.0: You can also use these convenience aliases: sw (startswith), ew (endswith), rx (regex) and has (contains).

Examples:

  • Query(module_in=['re', 'sre', 'sre_parse']) will match events from any of those modules.
  • ~Query(module_in=['re', 'sre', 'sre_parse']) will match events from any modules except those.
  • Query(module_startswith=['re', 'sre', 'sre_parse']) will match any events from modules that starts with either of those. That means repr will match!
  • Query(module_regex='(re|sre.*)$') will match any events from re or anything that starts with sre.

Note

If you want to filter out stdlib stuff you’re better off with using Query(stdlib=False).

Activation

You can activate Hunter in three ways.

from code

import hunter
hunter.trace(
    ...
)

with an environment variable

Set the PYTHONHUNTER environment variable. Eg:

PYTHONHUNTER="module='os.path'" python yourapp.py

On Windows you’d do something like:

set PYTHONHUNTER=module='os.path'
python yourapp.py

The activation works with a clever .pth file that checks for that env var presence and before your app runs does something like this:

from hunter import *
trace(
    <whatever-you-had-in-the-PYTHONHUNTER-env-var>
)

That also means that it will do activation even if the env var is empty, eg: PYTHONHUNTER="".

with a CLI tool

If you got an already running process you can attach to it with hunter-trace. See Remote tracing for details.

Remote tracing

Hunter supports tracing local processes, with two backends: manhole and GDB. For now Windows isn’t supported.

Using GDB is risky (if anything goes wrong your process will probably be hosed up badly) so the Manhole backend is recommended. To use it:

from hunter import remote
remote.install()

You should put this somewhere where it’s run early in your project (settings or package’s __init__.py file).

The remote.install() takes same arguments as manhole.install(). You’ll probably only want to use verbose=False

The CLI

usage: hunter-trace [-h] -p PID [-t TIMEOUT] [--gdb] [-s SIGNAL]
                [OPTIONS [OPTIONS ...]]
positional arguments:
OPTIONS
optional arguments:
-h, --help show this help message and exit
-p PID, --pid PID
 A numerical process id.
-t TIMEOUT, --timeout TIMEOUT
 Timeout to use. Default: 1 seconds.
--gdb Use GDB to activate tracing. WARNING: it may deadlock the process!
-s SIGNAL, --signal SIGNAL
 Send the given SIGNAL to the process before connecting.

The OPTIONS are hunter.trace() arguments.

Cookbook

When in doubt, use Hunter.

Walkthrough

Sometimes you just want to get an overview of an unfamiliar application code, eg: only see calls/returns/exceptions.

In this situation, you could use something like ~Q(kind="line"),~Q(module_in=["six","pkg_resources"]),~Q(filename=""),stdlib=False. Lets break that down:

  • ~Q(kind="line") means skip line events (~ is a negation of the filter).
  • stdlib=False means we don’t want to see anything from stdlib.
  • ~Q(module_in=["six","pkg_resources")] means we’re tired of seeing stuff from those modules in site-packages.
  • ~Q(filename="") is necessary for filtering out events that come from code without a source (like the interpreter bootstrap stuff).

You would run the application (in Bash) like:

PYTHONHUNTER='~Q(kind="line"),~Q(module_in=["six","pkg_resources"]),~Q(filename=""),stdlib=False' myapp (or python myapp.py)

Additionally you can also add a depth filter (eg: depth_lt=10) to avoid too deep output.

Packaging

I frequently use Hunter to figure out how distutils/setuptools work. It’s very hard to figure out what’s going on by just looking at the code - lots of stuff happens at runtime. If you ever tried to write a custom command you know what I mean.

To show everything that is being run:

PYTHONHUNTER='module_startswith=["setuptools", "distutils", "wheel"]' python setup.py bdist_wheel

If you want too see some interesting variables:

PYTHONHUNTER='module_startswith=["setuptools", "distutils", "wheel"], actions=[CodePrinter, VarsPrinter("self.bdist_dir")]' python setup.py bdist_wheel

Typical

Normally you’d only want to look at your code. For that purpose, there’s the stdlib option. Set it to False.

Building a bit on the previous example, if I have a build Distutils command and I only want to see my code then I’d run this:

PYTHONHUNTER='stdlib=False' python setup.py build

But this also means I’d be seeing anything from site-packages. I could filter on only the events from the current directory (assuming the filename is going to be a relative path):

PYTHONHUNTER='~Q(filename_startswith="/")' python setup.py build

Needle in the haystack

If the needle might be though the stdlib then you got not choice. But some of the hay is very verbose and useless, like stuff from the re module.

Note that there are few “hidden” modules like sre, sre_parse, sre_compile etc. You can filter that out with:

~Q(module_regex="(re|sre.*)$")

Although filtering out that regex stuff can cut down lots of useless output you usually still get lots of output.

Another way, if you got at least some vague idea of what might be going on is to “grep” for sourcecode. Example, to show all the code that does something with a build_dir property:

source_contains=".build_dir"

You could even extend that a bit to dump some variables:

source_contains=".build_dir", actions=[CodePrinter, VarsPrinter("self.build_dir")]

Stop after N calls

Say you want to stop tracing after 1000 events, you’d do this:

~Q(calls_gt=1000, action=Stop)

Explanation:

Q(calls_gt=1000, action=Stop) will translate to When(Query(calls_gt=1000), Stop)

Q(calls_gt=1000) will return True when 1000 call count is hit.

When(something, Stop) will call Stop when something returns True. However it will also return the result of something - the net effect being nothing being shown up to 1000 calls. Clearly not what we want …

So then we invert the result, ~When(...) is the same as Not(When).

This may not seem intuitive but for now it makes internals simpler. If When would always return True then Or(When, When) would never run the second When and we’d need to have all sorts of checks for this. This may change in the future however.

“Probe” - lightweight tracing

Based on Robert Brewer’s FunctionProbe example.

The use-case is that you’d like to trace a huge application and running a tracer (even a cython one) would have a too great impact. To solve this you’d start the tracer only in placer where it’s actually needed.

To make this work you’d monkeypatch the function that needs the tracing. This example uses aspectlib:

def probe(qualname, *actions, **filters):
    def tracing_decorator(func):
        @functools.wraps(func)
        def tracing_wrapper(*args, **kwargs):
            # create the Tracer manually to avoid spending time in likely useless things like:
            # - loading PYTHONHUNTERCONFIG
            # - setting up the clear_env_var or thread_support options
            # - atexit cleanup registration
            with hunter.Tracer().trace(hunter.When(hunter.Query(**filters), *actions)):
                return func(*args, **kwargs)

        return tracing_wrapper

    aspectlib.weave(qualname, tracing_decorator)  # this does the monkeypatch

Suggested use:

  • to get the regular tracing for that function:

    probe('module.func', hunter.VarsPrinter('var1', 'var2'))
    
  • to log some variables at the end of the target function, and nothing deeper:

    probe('module.func', hunter.VarsPrinter('var1', 'var2'), kind="return", depth=0)
    

Another interesting thing is that you may note that you can reduce the implementation of the probe function down to just:

def probe(qualname, *actions, **kwargs):
    aspectlib.weave(qualname, functools.partial(hunter.wrap, actions=actions, **kwargs))

It will work the same, hunter.wrap being a decorator. However, while hunter.wrap offers the convenience of tracing just inside the target function (eg: probe('module.func', local=True)) it will also add a lot of extra filtering to trim irrelevant events from around the function (like return from tracer setup, and the internals of the decorator), in addition to what hunter.trace() does. Not exactly lightweight…

Silenced exception runtime analysis

Finding code that discards exceptions is sometimes really hard.

While this is easy to find with a grep "except:" -R .:

def silenced_easy():
    try:
        error()
    except:
        pass

Variants of this ain’t easy to grep:

def silenced_easy():
    try:
        error()
    except Exception:
        pass

If you can’t simply review all the sourcecode then runtime analysis is one way to tackle this:

class DumpExceptions(hunter.CodePrinter):
    events = ()
    depth = 0
    count = 0
    exc = None

    def __init__(self, max_count=10, **kwargs):
        self.max_count = max_count
        self.backlog = collections.deque(maxlen=5)
        super(DumpExceptions, self).__init__(**kwargs)

    def __call__(self, event):
        self.count += 1
        if event.kind == 'exception':  # something interesting happened ;)
            self.events = list(self.backlog)
            self.events.append(event.detach(self.try_repr))
            self.exc = self.try_repr(event.arg[1])
            self.depth = event.depth
            self.count = 0
        elif self.events:
            if event.depth > self.depth:  # too many details
                return
            elif event.depth < self.depth and event.kind == 'return':  # stop if function returned
                op = event.code.co_code[event.frame.f_lasti]
                op = op if isinstance(op, int) else ord(op)
                if op == RETURN_VALUE:
                    self.output("{BRIGHT}{fore(BLUE)}{} tracing {} on {}{RESET}\n",
                                ">" * 46, event.function, self.exc)
                    for event in self.events:
                        super(DumpExceptions, self).__call__(event)
                    if self.count > 10:
                        self.output("{BRIGHT}{fore(BLACK)}{} too many lines{RESET}\n",
                                    "-" * 46)
                    else:
                        self.output("{BRIGHT}{fore(BLACK)}{} function exit{RESET}\n",
                                    "-" * 46)
                self.events = []
                self.exc = None
            elif self.count < self.max_count:
                self.events.append(event.detach(self.try_repr))
        else:
            self.backlog.append(event.detach(self.try_repr))

Take note about the use of detach() and output().

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

Contributing

Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.

Bug reports

When reporting a bug please include:

  • Your operating system name and version.
  • Any details about your local setup that might be helpful in troubleshooting.
  • Detailed steps to reproduce the bug.

Documentation improvements

Hunter could always use more documentation, whether as part of the official Hunter docs, in docstrings, or even on the web in blog posts, articles, and such.

Feature requests and feedback

The best way to send feedback is to file an issue at https://github.com/ionelmc/python-hunter/issues.

If you are proposing a feature:

  • Explain in detail how it would work.
  • Keep the scope as narrow as possible, to make it easier to implement.
  • Remember that this is a volunteer-driven project, and that code contributions are welcome :)

Development

To set up python-hunter for local development:

  1. Fork python-hunter (look for the “Fork” button).

  2. Clone your fork locally:

    git clone git@github.com:ionelmc/python-hunter.git
    
  3. Create a branch for local development:

    git checkout -b name-of-your-bugfix-or-feature
    

    Now you can make your changes locally.

  4. When you’re done making changes, run all the checks, doc builder and spell checker with tox one command:

    tox
    
  5. Commit your changes and push your branch to GitHub:

    git add .
    git commit -m "Your detailed description of your changes."
    git push origin name-of-your-bugfix-or-feature
    
  6. Submit a pull request through the GitHub website.

Pull Request Guidelines

If you need some code review or feedback while you’re developing the code just make the pull request.

For merging, you should:

  1. Include passing tests (run tox) [1].
  2. Update documentation when there’s new API, functionality etc.
  3. Add a note to CHANGELOG.rst about the changes.
  4. Add yourself to AUTHORS.rst.
[1]

If you don’t have all the necessary python versions available locally you can rely on Travis - it will run the tests for each change you add in the pull request.

It will be slower though …

Tips

To run a subset of tests:

tox -e envname -- pytest -k test_myfeature

To run all the test environments in parallel (you need to pip install detox):

detox

Authors

Changelog

3.0.4 (2019-10-26)

  • Really fixed stream setup in actions (using force_colors without any stream was broken). See: ColorStreamAction.
  • Fixed __repr__ for the From predicate to include watermark.
  • Added binary wheels for Python 3.8.

3.0.3 (2019-10-13)

3.0.2 (2019-10-10)

  • Fixed setting stream from PYTHONHUNTERCONFIG environment variable. See: ColorStreamAction.
  • Fixed a couple minor documentation issues.

3.0.1 (2019-06-17)

  • Fixed issue with coloring missing source message (coloring leaked into next line).

3.0.0 (2019-06-17)

  • The package now uses setuptools-scm for development builds (available at https://test.pypi.org/project/hunter/). As a consequence installing the sdist will download setuptools-scm.

  • Recompiled cython modules with latest Cython. Hunter can be installed without any Cython, as before.

  • Refactored some of the cython modules to have more typing information and not use deprecated property syntax.

  • Replaced unsafe_repr option with repr_func. Now you can use your custom repr function in the builtin actions. BACKWARDS INCOMPATIBLE

  • Fixed buggy filename handling when using Hunter in ipython/jupyter. Source code should be properly displayed now.

  • Removed globals option from VarsPrinter action. Globals are now always looked up. BACKWARDS INCOMPATIBLE

  • Added support for locals in VarsPrinter action. Now you can do VarsPrinter('len(foobar)').

  • Always pass module_globals dict to linecache methods. Source code from PEP-302 loaders is now printed properly. Contributed by Mikhail Borisov in #65.

  • Various code cleanup, style and docstring fixing.

  • Added hunter.From() helper to allow passing in filters directly as keyword arguments.

  • Added hunter.event.Event.detach() for storing events without leaks or side-effects (due to prolonged references to Frame objects, local or global variables).

  • Refactored the internals of actions for easier subclassing.

    Added the filename_prefix(), output(), pid_prefix(), thread_prefix(), try_repr() and try_source() methods to the hunter.actions.ColorStreamAction baseclass.

  • Added hunter.actions.VarsSnooper - a PySnooper-inspired variant of VarsPrinter. It will record and show variable changes, with the risk of leaking or using too much memory of course :)

  • Fixed tracers to log error and automatically stop if there’s an internal failure. Previously error may have been silently dropped in some situations.

2.2.1 (2019-01-19)

  • Fixed a link in changelog.
  • Fixed some issues in the Travis configuration.

2.2.0 (2019-01-19)

  • Added hunter.predicates.From predicate for tracing from a specific point. It stop after returning back to the same call depth with a configurable offset.
  • Fixed PYTHONHUNTERCONFIG not working in some situations (config values were resolved at the wrong time).
  • Made tests in CI test the wheel that will eventually be published to PyPI (tox-wheel).
  • Made event.stdlib more reliable: pkg_resources is considered part of stdlib and few more paths will be considered as stdlib.
  • Dumbed down the get_peercred check that is done when attaching with hunter-trace CLI (via hunter.remote.install()). It will be slightly insecure but will work on OSX.
  • Added OSX in the Travis test grid.

2.1.0 (2018-11-17)

  • Made threading_support on by default but output automatic (also, now 1 or 0 allowed).
  • Added pid_alignment and force_pid action options to show a pid prefix.
  • Fixed some bugs around __eq__ in various classes.
  • Dropped Python 3.3 support.
  • Dropped dependency on fields.
  • Actions now repr using a simplified implementation that tries to avoid calling __repr__ on user classes in order to avoid creating side-effects while tracing.
  • Added support for the PYTHONHUNTERCONFIG environment variable (stores defaults and doesn’t activate hunter).

2.0.2 (2017-11-24)

  • Fixed indentation in hunter.actions.CallPrinter action (shouldn’t deindent on exception).
  • Fixed option filtering in Cython Query implementation (filtering on tracer was allowed by mistake).
  • Various fixes to docstrings and docs.

2.0.1 (2017-09-09)

  • Now Py_AddPendingCall is used instead of acquiring the GIL (when using GDB).

2.0.0 (2017-09-02)

  • Added the hunter.event.Event.count and hunter.event.Event.calls` attributes.
  • Added the lt/lte/gt/gte lookups.
  • Added convenience aliases for startswith (sw), endswith (ew), contains (has) and regex (rx).
  • Added a convenience hunter.wrap() decorator to start tracing around a function.
  • Added support for remote tracing (with two backends: manhole and GDB) via the hunter-trace bin. Note: Windows is NOT SUPPORTED.
  • Changed the default action to hunter.actions.CallPrinter. You’ll need to use action=CodePrinter if you want the old output.

1.4.1 (2016-09-24)

  • Fix support for getting sources for Cython module (it was broken on Windows and Python3.5+).

1.4.0 (2016-09-24)

  • Added support for tracing Cython modules (#30). A # cython: linetrace=True stanza or equivalent is required in Cython modules for this to work.

1.3.0 (2016-04-14)

1.2.2 (2016-01-28)

  • Fix broken import. Require fields>=4.0.
  • Simplify a string check in Cython code.

1.2.1 (2016-01-27)

  • Fix “KeyError: ‘normal’” bug in hunter.actions.CallPrinter. Create the NO_COLORS dict from the COLOR dicts. Some keys were missing.

1.2.0 (2016-01-24)

1.1.0 (2016-01-21)

  • Implemented a destructor (__dealloc__) for the Cython tracer.
  • Improved the restoring of the previous tracer in the Cython tracer (use PyEval_SetTrace) directly.
  • Removed tracer as an allowed filtering argument in hunter.Query.
  • Add basic validation (must be callable) for positional arguments and actions passed into hunter.Q. Closes #23.
  • Fixed stdlib checks (wasn’t very reliable). Closes #24.

1.0.2 (2016-01-05)

  • Fixed missing import in setup.py.

1.0.1 (2015-12-24)

  • Fix a compile issue with the MSVC compiler (seems it don’t like the inline option on the fast_When_call).

1.0.0 (2015-12-24)

  • Implemented fast tracer and query objects in Cython. MAY BE BACKWARDS INCOMPATIBLE

    To force using the old pure-python implementation set the PUREPYTHONHUNTER environment variable to non-empty value.

  • Added filtering operators: contains, startswith, endswith and in. Examples:

    • Q(module_startswith='foo' will match events from foo, foo.bar and foobar.
    • Q(module_startswith=['foo', 'bar'] will match events from foo, foo.bar, foobar, bar, bar.foo and baroo .
    • Q(module_endswith='bar' will match events from foo.bar and foobar.
    • Q(module_contains='ip' will match events from lipsum.
    • Q(module_in=['foo', 'bar'] will match events from foo and bar.
    • Q(module_regex=r"(re|sre.*)\b") will match events from ``re, re.foobar, srefoobar but not from repr.
  • Removed the merge option. Now when you call hunter.trace(...) multiple times only the last one is active. BACKWARDS INCOMPATIBLE

  • Remove the previous_tracer handling. Now when you call hunter.trace(...) the previous tracer (whatever was in sys.gettrace()) is disabled and restored when hunter.stop() is called. BACKWARDS INCOMPATIBLE

  • Fixed CodePrinter to show module name if it fails to get any sources.

0.6.0 (2015-10-10)

  • Added a clear_env_var option on the tracer (disables tracing in subprocess).
  • Added force_colors option on hunter.actions.VarsPrinter and hunter.actions.CodePrinter.
  • Allowed setting the stream to a file name (option on hunter.actions.VarsPrinter and hunter.actions.CodePrinter).
  • Bumped up the filename alignment to 40 cols.
  • If not merging then self is not kept as a previous tracer anymore. Closes #16.
  • Fixed handling in VarsPrinter: properly print eval errors and don’t try to show anything if there’s an AttributeError. Closes #18.
  • Added a stdlib boolean flag (for filtering purposes). Closes #15.
  • Fixed broken frames that have “None” for filename or module (so they can still be treated as strings).
  • Corrected output files in the install_lib command so that pip can uninstall the pth file. This only works when it’s installed with pip (sadly, setup.py install/develop and pip install -e will still leave pth garbage on pip uninstall hunter).

0.5.1 (2015-04-15)

0.5.0 (2015-04-06)

0.4.0 (2015-03-29)

  • Disabled colors for Jython. Contributed by Claudiu Popa in #12.
  • Test suite fixes for Windows. Contributed by Claudiu Popa in #11.
  • Added an introduction section in the docs.
  • Implemented a prettier fallback for when no sources are available for that frame.
  • Implemented fixups in cases where you use action classes as a predicates.

0.3.1 (2015-03-29)

  • Forgot to merge some commits …

0.3.0 (2015-03-29)

  • Added handling for internal repr failures.
  • Fixed issues with displaying code that has non-ascii characters.
  • Implemented better display for call frames so that when a function has decorators the function definition is shown (instead of just the first decorator). See: #8.

0.2.1 (2015-03-28)

  • Added missing color entry for exception events.
  • Added hunter.event.Event.line property. It returns the source code for the line being run.

0.2.0 (2015-03-27)

  • Added color support (and colorama as dependency).
  • Added support for expressions in hunter.actions.VarsPrinter.
  • Breaking changes:
  • Improved error reporting for env variable activation (PYTHONHUNTER).
  • Fixed env var activator (the .pth file) installation with setup.py install (the “egg installs”) and setup.py develop/pip install -e (the “egg links”).

0.1.0 (2015-03-22)

  • First release on PyPI.

Indices and tables