R
Ron_Adam
I was having some difficulty figuring out just what was going on with
decorators. So after a considerable amount of experimenting I was
able to take one apart in a way. It required me to take a closer look
at function def's and call's, which is something I tend to take for
granted.
I'm not sure this is 100%, or if there are other ways to view it, but
it seems to make sense when viewed this way.
Is there a way to do this same thing in a more direct way? Like
taking values off the function stack directly. How much of it get's
optimized out by the compiler?
#
# Follow the numbers starting with zero.
#
# (0) Read defined functions into memory
def decorator(d_arg): # (7) Get 'Goodbye' off stack
def get_function(function): # (8) Get func object off stack
def wrapper(f_arg): # (9) Get 'Hello' off stack
new_arg = f_arg+'-'+d_arg
result = function(new_arg) # (10) Put new_arg on stack
# (11) Call func object
return result # (14) Return result to wrapper
return wrapper # (15) Return result to get_function
return get_function # (16) Return result to caller of func
@decorator('Goodbye') # (5) Put 'Goodbye' on stack
# (6) Do decorator
def func(s): # (12) Get new_arg off stack
return s # (13) Return s to result
# (1) Done Reading definitions
print func('Hello') # (2) Put 'Hello' on stack
# (3) Put func object on stack
# (4) Do @decorator
# (17) print 'Hello-Goodbye'
# Hello-Goodbye
decorators. So after a considerable amount of experimenting I was
able to take one apart in a way. It required me to take a closer look
at function def's and call's, which is something I tend to take for
granted.
I'm not sure this is 100%, or if there are other ways to view it, but
it seems to make sense when viewed this way.
Is there a way to do this same thing in a more direct way? Like
taking values off the function stack directly. How much of it get's
optimized out by the compiler?
#
# Follow the numbers starting with zero.
#
# (0) Read defined functions into memory
def decorator(d_arg): # (7) Get 'Goodbye' off stack
def get_function(function): # (8) Get func object off stack
def wrapper(f_arg): # (9) Get 'Hello' off stack
new_arg = f_arg+'-'+d_arg
result = function(new_arg) # (10) Put new_arg on stack
# (11) Call func object
return result # (14) Return result to wrapper
return wrapper # (15) Return result to get_function
return get_function # (16) Return result to caller of func
@decorator('Goodbye') # (5) Put 'Goodbye' on stack
# (6) Do decorator
def func(s): # (12) Get new_arg off stack
return s # (13) Return s to result
# (1) Done Reading definitions
print func('Hello') # (2) Put 'Hello' on stack
# (3) Put func object on stack
# (4) Do @decorator
# (17) print 'Hello-Goodbye'
# Hello-Goodbye