line_profiler: what am I doing wrong?

Neal Becker ndbecker2 at gmail.com
Tue Feb 10 19:45:05 EST 2015


Steven D'Aprano wrote:

> Neal Becker wrote:
> 
>> I inserted
>> @profile
>> def run(...)
>> 
>> into a module-level global function called 'run'.  Something is very wrong
>> here. 1. profile results were written before anything even ran
>> 2. profile is not defined?
> 
> Well, is it defined? Where does it come from?
> 
> If you defined it yourself, it needs to be defined before you can use it.
> This won't work:
> 
> 
> @profile
> def run(...)
> 
> def profile(func): ...
> 
> 
> Swap the order of profile and run and it should work. (Give or take any
> additional bugs in your code.)
> 
> 
> If you've imported it from an external module, how did you import it?
> 
> 
> import some_module
> 
> @some_module.profile
> def run(...)
> 
> 
> should work. So will this:
> 
> 
> from some_module import profile
> 
> @profile
> def run(...)
> 
> 
> But this won't:
> 
> 
> import some_module
> 
> @profile
> def run(...)
> 
> 
> and will fail with NameError, exactly as you are experiencing.
> 
> 
> 
> 

To quote from https://pypi.python.org/pypi/line_profiler/

$ kernprof -l script_to_profile.py
kernprof will create an instance of LineProfiler and insert it into the 
__builtins__ namespace with the name profile. It has been written to be used as 
a decorator, so in your script, you decorate the functions you want to profile 
with @profile.

@profile
def slow_function(a, b, c):
    ...

I've used it before (maybe 1 year ago), don't know why it isn't working now.
-- 
-- Those who don't understand recursion are doomed to repeat it




More information about the Python-list mailing list