Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 629
Laura Avatar asked Oct 28 '15 19:10

Laura


People also ask

How do I create a custom decorator in Python?

To create a decorator function in Python, I create an outer function that takes a function as an argument. There is also an inner function that wraps around the decorated function. To use a decorator ,you attach it to a function like you see in the code below.

How do you make an optional parameter in Python?

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.

Are Python decorators necessary?

Needless to say, Python's decorators are incredibly useful. Not only can they be used to slow down the time it takes to write some code, but they can also be incredibly helpful at speeding up code. Not only are decorators incredibly useful when you find them about, but it is also a great idea to write your own.


1 Answers

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

if 'profile' not in globals():
    def profile(func):
        return func
like image 60
Daniel Avatar answered Sep 29 '22 00:09

Daniel