'Returning a value 2 stack frames up in Python?
Is it possible to have a function return 2 stack frames up in Python, without having a wrapper function or intermediate handling in the middle function?
Minimum Example:
def foo():
bar()
return 1
def bar():
return 2 # Want to change this to make foo's return value 2, not 1
foo() # Want this to return 2
Of course, this would be possible by modifying foo
, but I'm wondering if there's a statement in Python to return the value of 2
from bar
several stack frames up, for example instead of foo
's return value of 1
.
I've tried looking into some introspection techniques, but Python doesn't seem to support much.
Maybe this approach should never be taken, because it breaks concepts of encapsulation?
Solution 1:[1]
I'm wondering if there's a statement in Python to return the value of 2 from bar several stack frames up, for example instead of foo's return value of 1.
There is no such statement. What you describe is certainly possible in python, but as a day-to-day programming technique rather than a debugging technique it's completely mental.
Maybe this approach should never be taken
Yes! (In python, and language with cheap pass-by-reference everywhere.) Python isn't a push-n-pop-the-stack language...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | 2e0byo |