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

有帮助吗?

解决方案

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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top