Skip to main content
Edited title and removed language tag.
Link
martineau
  • 124.1k
  • 29
  • 181
  • 319

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

Source Link
elifiner
  • 7.7k
  • 9
  • 43
  • 48

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

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

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

or without them (for instance to redirect the output to stderr by default):

@redirect_output def foo(): .... 

Is that at all possible?

Note that I'm not looking for a different solution to the problem of redirecting output, it's just an example of the syntax I'd like to achieve.