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?
Asked
Active
Viewed 1,239 times
1

Yaroslav Bulatov
- 57,332
- 22
- 139
- 197
1 Answers
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
- 145,886
- 38
- 333
- 352
-
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