decorators only when __debug__ == True

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Mar 29 22:11:09 EDT 2010


On Mon, 29 Mar 2010 17:54:26 -0700, LX wrote:

> Hi all, I have a question about decorators. I would like to use them for
> argument checking, and pre/post conditions. However, I don't want the
> additional overhead when I run in non-debug mode. I could do something
> like this, using a simple trace example.


def decorator(func):
    if __debug__:
        @functools.wraps(func)
        def inner(*args, **kwargs):
            preprocess()
            result = func(*args, **kwargs)
            postprocess()
            return result
        return inner
    else:
        return func



-- 
Steven



More information about the Python-list mailing list