Search code examples
pythonpython-3.xmethodswrapperline-profiler

Python - Manually wrapping a method (Specifically, am asking about line-profiler by robert kern)


Wrapping a function is no problem: How do I use line_profiler (from Robert Kern)?

from line_profiler import LineProfiler
import random

def do_stuff(numbers):
    s = sum(numbers)
    l = [numbers[i]/43 for i in range(len(numbers))]
    m = ['hello'+str(numbers[i]) for i in range(len(numbers))]

numbers = [random.randint(1,100) for i in range(1000)]
lp = LineProfiler()
lp_wrapper = lp(do_stuff)
lp_wrapper(numbers)
lp.print_stats()

However, what I can't seem to figure out it is applying this same technique to methods.

Let's say I attempt to use the same technique on a method:

class Foo:
    def method(self):
        return 1

obj = Foo()

lp = LineProfiler()
lp_wrapper = lp(method)
obj.lp_wrapper()  # Causes an error since Foo does not have a method called "lp_wrapper"

What is the best way to fix this error? Thanks.


Solution

  • The best answer comes from schwobaseggl: "Have you tried lp_wrapper = lp(obj.method)"

    It turns out that this is the way you wrap methods.