How to create a Python decorator that can be used either with or without parameters?

前端 未结 13 1643
死守一世寂寞
死守一世寂寞 2020-11-30 21:26

I\'d like to create a Python decorator that can be used either with parameters:

@redirect_output(\"somewhere.log\")
def foo():
    ....

or

13条回答
  •  醉酒成梦
    2020-11-30 21:40

    Generally you can give default arguments in Python...

    def redirect_output(fn, output = stderr):
        # whatever
    

    Not sure if that works with decorators as well, though. I don't know of any reason why it wouldn't.

提交回复
热议问题