How would you write a @debuggable decorator in python?

前端 未结 5 783
孤街浪徒
孤街浪徒 2020-12-24 03:57

When debugging, I like to print out all the inputs and outputs of a function (I know I need a better IDE, but humour me, this could be used for error reporting). So, I\'d id

5条回答
  •  爱一瞬间的悲伤
    2020-12-24 04:35

    I think what you're after isn't really a debugging decorator, but more of a logging decorator.

    It might make sense to use Python's logging module so you can have more fine grained control over the logging itself. For example you would be able to output to a file for later analysing the output.

    The decorator might then look something more like:

    
    import logging
    
    logger = logging.getLogger('TraceLog')
    # TODO configure logger to write to file/stdout etc, it's level etc
    
    
    def logthis(level):
        def _decorator(fn):
            def _decorated(*arg,**kwargs):
                logger.log(level, "calling '%s'(%r,%r)", fn.func_name, arg, kwargs)
                ret=fn(*arg,**kwargs)
                logger.log(level, "called '%s'(%r,%r) got return value: %r", fn.func_name, arg, kwargs, ret)
                return ret
            return _decorated
        return _decorator
    
    @logthis(logging.INFO)
    def myfunc(this,that):
        return this+that
    
    

    Then if you configure the logger to output to stderr you'd see:

    
    >>> logger.setLevel(logging.INFO)
    >>> handler=logging.StreamHandler()
    >>> logger.addHandler(handler)
    >>> myfunc(1,2)
    calling 'myfunc'((1, 2),{})
    called 'myfunc'((1, 2),{}) got return value: 3
    
    

提交回复
热议问题