简体   繁体   中英

How to make an optional decorator in Python

I have a set of python scripts that I would like to profile with kernprof https://github.com/rkern/line_profiler but I also want to be able to run it during normal execution without kernprof.

What is an elegant way of ignoring the undefined @profile during execution without kernprof? Or any other decorator.

Example Code:

    @profile
    def hello():
        print('Testing')

    hello()

Running with:

    kernprof -l test.py

Correctly executes the profiler on @profile methods

Running with:

    python test.py 

Returns an error:

    Traceback (most recent call last):
    File "test.py", line 1, in <module>
    @profile
    NameError: name 'profile' is not defined

Would like to avoid catching this error everywhere as I want the code to execute as if @profile is a no-op when its not called with kernprof.

Thanks! -Laura

Edit: I ended up using cProfile with kcachegrind and avoiding decorators altogether.

Using cProfile results with KCacheGrind

python -m cProfile -o profile_data.pyprof run_cli.py

pyprof2calltree -i profile_data.pyprof && qcachegrind profile_data.pyprof.log

Define a no-op decorator if not executed from kernprof:

if 'profile' not in globals():
    def profile(func):
        return func

A variant over the method proposed by Daniel, would be to use the following one-liner, and then comment it in and out depending on your need for profiling or not:

# Optional no-op decorator, comment when you want to profile
def profile(func): return func

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM