1

Popular solution for Python line profiling seems to be kernprof -l script.py, which requires adding "@profile" decorators to functions you want to profile. Running the same code without as python script.py will complain "name 'profile' not defined" so you have to comment out @profile lines. What's a good work-around to switch between "profile" and non-profile modes without having to comment out those lines?

Yaroslav Bulatov
  • 55,467
  • 20
  • 132
  • 186

1 Answers1

4

You could try to add something like this at the top of your script:

try:
    profile  # throws an exception when profile isn't defined
except NameError:
    profile = lambda x: x   # if it's not defined simply ignore the decorator.

That way you define the profile function as no-op decorator if it's not defined.

MSeifert
  • 133,177
  • 32
  • 312
  • 322
  • But if you try to run the kernprof like `kernprof -l --setup script.py script.py`, this overrides the profiler even on the second run. – JonnyRobbie Oct 01 '21 at 14:29