Filtering

Banana

Filtering is sometimes needed when the output of Python Call Graph is overwhelming, or if you want to only measure a small portion of your program. The filtering guide below is based on the filter.py example.

Let’s demonstrate with a class that can eat a banana:

import time


class Banana:

    def __init__(self):
        pass

    def eat(self):
        self.secret_function()
        self.chew()
        self.swallow()

    def secret_function(self):
        time.sleep(0.2)

    def chew(self):
        pass

    def swallow(self):
        pass

No Filter

The code to measure it without any configuration, apart from the output file:

#!/usr/bin/env python

from pycallgraph import PyCallGraph
from pycallgraph.output import GraphvizOutput

from banana import Banana


graphviz = GraphvizOutput(output_file='filter_none.png')

with PyCallGraph(output=graphviz):
    banana = Banana()
    banana.eat()

The Graphviz output after running the measurement code:

../_images/filter_none.png

Hide the secret

Probably need to hide that secret_function. Create a GlobbingFilter which excludes secret_function along with pycallgraph so we don’t see the internals. Add that filter to the config option called trace_filter:

#!/usr/bin/env python

from pycallgraph import PyCallGraph
from pycallgraph import Config
from pycallgraph import GlobbingFilter
from pycallgraph.output import GraphvizOutput

from banana import Banana


config = Config()
config.trace_filter = GlobbingFilter(exclude=[
    'pycallgraph.*',
    '*.secret_function',
])

graphviz = GraphvizOutput(output_file='filter_exclude.png')

with PyCallGraph(output=graphviz, config=config):
    banana = Banana()
    banana.eat()

And the output:

../_images/filter_exclude.png

You can also use “include” as well as “exclude” in the GlobbingFilter.

Maximum Depth

Let’s say you’re only interested in the first level of calls. You can specify this using config.max_depth:

#!/usr/bin/env python

from pycallgraph import PyCallGraph
from pycallgraph import Config
from pycallgraph.output import GraphvizOutput

from banana import Banana


config = Config(max_depth=1)
graphviz = GraphvizOutput(output_file='filter_max_depth.png')

with PyCallGraph(output=graphviz, config=config):
    banana = Banana()
    banana.eat()

And the output:

../_images/filter_max_depth.png