Skip to content

Instantly share code, notes, and snippets.

@seanjensengrey
Last active August 29, 2015 14:25
Show Gist options
  • Save seanjensengrey/84beab9d6f907c0dc433 to your computer and use it in GitHub Desktop.
Save seanjensengrey/84beab9d6f907c0dc433 to your computer and use it in GitHub Desktop.
dynamic scope like in the good old days
import sys
import pdb
import types
__doc__ = """
This example shows how to search back through the stack
for a local and return a reference to calling function.
Useful hack for when you are deep in the hierarchy and
need something the n-th calling function has w/o having
to make a global.
"""
class Log:
def msg(self, alert, msg):
if alert:
print "**", msg, "**"
else:
print msg
def stack_search(name, _type=None):
"locals for a locals <name> of optional type <_type>"
try:
i = 0
while True:
frame = sys._getframe(i)
if name in frame.f_locals:
if _type != None:
o = frame.f_locals[name]
if type(o) == _type:
return o
else:
return frame.f_locals[name]
i += 1
except ValueError:
return None
def one():
l = Log()
l.msg(True, "calling two()")
two()
def two():
three()
def three():
four()
def four():
logger = stack_search('l', types.InstanceType)
if logger:
logger.msg(True, "sending a message from way down here!")
one()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment