0

I guess, the answer is "no", since someone else asked something similar a while ago, but a lot happens in 7 years..

In some quite non-pythonic experiment I'd like to write a decorator which calls it's wrapped function and react on what's happening inside this function.

Currently a detail bugs me:

def my_decorator(fn):
    print(execute_and_get_value(fn, "some_value")

@my_decorator
def foo():
   some_value = 23

my_decorator should run fn() on module load (that's the part which works) and then somehow get the value of some_value defined in foo(). All I want to know if that's technically possible at all.

One approach would be to let foo() access a member to some global object instead of writing to a local variable and just read that global object afterwards. But that's cheating.

Is that possible or resp. is there a way to prove this impossible?

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
frans
  • 8,868
  • 11
  • 58
  • 132
  • 1
    No, this is not possible. Local variables do not even exist by name in (C)Python. If you look at the output of `dis.dis(foo)`, you'll see `some_value` is basically replaced by an integer index in the body of `foo`. Your decorator would have to examine the *source* code of `foo` in order to determine which index represented the original `some_value`. – chepner Apr 23 '23 at 15:16
  • 1
    The variable only comes into existence when the function is executed, and ceases to exist when the function ends. The variable only exists while the function is running, and while the function is running, no other "outside code" can be running to inspect it. So no, this isn't possible. For some very specific cases you can maybe find some workaround, like inspecting the function's source code and extract the value that way, but that won't help if you need the value of a dynamic calculation. – deceze Apr 23 '23 at 15:17
  • 1
    I'm going to backtrack slightly on my comment. For debugging purposes, the name is still retained in the compiled byte code, though digging it out for purposes of actually *using* it should still be considered infeasible. – chepner Apr 23 '23 at 15:25
  • Thanks for the comments, since they actually answer my question while the suggested answered question addresses a totally different question (also on a totally different level IMO) – frans Apr 23 '23 at 15:44

0 Answers0