Thursday 15 April 2010

python - Decorated function along with original, without having to re-write the function -



python - Decorated function along with original, without having to re-write the function -

if have decorator , function, utilize decorated function along undecorated version of function, do?

i haven't used decorators much , can find, seems if have write out 2 separate functions accomplish this, or phone call decorator function parameter can confusing when dealing multiple decorators.

to work around this, writing out function, utilize roundabout way of decorating function , returning decorated function after fact. have access both undecorated , decorated versions of function. can tell, method in accomplished looked downwards upon little bit, has been working me so far. cannot imagine best way go this.

essentially, pass function want decorate, along decorator functions, method inspects functions text, adds @decorator syntax text, adds decorator functions __builtins__ module temporarily can exec text dictionary define new decorated function. new function object extracted dictionary , returned new decorated function.

i'm pretty sure not best way go this. don't imagine work in situations, don't want have phone call decorated functions or rewrite function every time.

don't utilize decorator decorator then. remember, decorator syntactic sugar, don't have utilize it.

the syntax:

@decorator_expr def decorated_func(): pass

is executed as:

def decorated_func(): pass decorated_func = decorator_expr(decorated_func)

to maintain 'original' , decorated version, then, assign output of decorator different name:

def foo(): pass foo_decorated = decorator_expr(foo)

alternatively, utilize decorator callable every time need decorated version:

result = decorator_expr(foo)()

python metaprogramming decorator

No comments:

Post a Comment