1

python's decorator is a sweet sugar. I use it to macro a function definition like these.

@logger(level="debug")
foo(var)

or

@repeat(3)
foo(var)

They are translate the foo function as parsing time, similar as macro. But I am seeking freedom to use decorate in run time.

foo(var)

or (note - apply decorator when executing foo(), rather then defining foo())

@logger(level="debug")
@repeat(5)
foo(var)

Q1) Does python give such freedom officially? I do not like using workarounds, since I will add/use more decorators in the future.

Q2) If not, does the following is the direct way to make the freedom happen? How to handle *args and **kwargs?

temp_foo = logger( level="debug", repeat(5, foo, *args) )
temp_foo(var)

Q3) Does python have proposal to support runtime decorator? Or may have some thoughts?

Thanks

MK at Soho
  • 322
  • 1
  • 3
  • 10
  • Decorators are evaluated at run-time in Python: http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python Maybe not in Java. – User Feb 13 '14 at 12:34
  • I read 739654 before. I should give a more specific interpret of runtime. The RUNTIME I expected is executing the function foo(), rather the defining it. – MK at Soho Feb 14 '14 at 01:48

1 Answers1

1

The decorator syntax, no. But you can still invoke them manually. It's probably best to only use decorators that have no side effects though, i.e. ones that don't modify the function passed to it.

logger(level="debug")(repeat(5)(foo))(var)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358