`TypeError:'module' object is not callable` occurs when I use the line profiler to perform performance statistics

Viewed 1421

I follow the [line profiler doc]https://github.com/pyutils/line_profiler to use line profiler, but TypeError will occur during runtime. Below is my program(file name is fib.py):

import profile


@profile
def primes(n):
    if n == 2:
        return [2]
    elif n < 2:
        return []
    s = range(3, n + 1, 2)
    mroot = n ** 0.5
    half = (n + 1) / 2 - 1
    i = 0
    m = 3
    while m <= mroot:
        if s[i]:
            j = (m * m - 3) / 2
            s[j] = 0
            while j < half:
                s[j] = 0
                j += m
        i = i + 1
        m = 2 * i + 3
    return [2] + [x for x in s if x]


primes(100)

The version of line profiler is 3.1.0, and the run command is kernprof -l -v fib.py.

The error detail is

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/bin/kernprof", line 8, in <module>
    sys.exit(main())
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/kernprof.py", line 226, in main
    execfile(script_file, ns, ns)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/kernprof.py", line 35, in execfile
    exec_(compile(f.read(), filename, 'exec'), globals, locals)
  File "fib.py", line 4, in <module>
    @profile.Profile(timer=None,bias=None)
TypeError: 'Profile' object is not callable

Is my usage incorrect or the profile decorator is not implemented?

2 Answers
import line_profiler
profile = line_profiler.LineProfiler()

You Should import the profiler like this and it should work.

After that use the profile to decorate your function

Or Use If you prefer to only import Profiler

from line_profiler import LineProfiler
profile = LineProfiler()

An alternative answer is to remove import profile without replacement. If you run the script via the kernprof command, you don't need to import anything in your code, but VS Code's autoimport feature loves to add import profile, which will cause problems.

Note that without imports, you have to remove or comment out the @profile decorators afterwards because otherwise you can only run your code via kernprof but not via a normal python call.

Related