Skip to content

Instantly share code, notes, and snippets.

@feth
Created March 26, 2012 05:47
Show Gist options
  • Save feth/2203254 to your computer and use it in GitHub Desktop.
Save feth/2203254 to your computer and use it in GitHub Desktop.
print invocation context
from inspect import currentframe, isfunction, ismethod, isclass, getframeinfo
def wannaknow(message):
#wander until correct frame
frame = currentframe()
interframe = frame.f_back
frame = interframe.f_back
if frame is None:
# stray call (direct call at module root)
location = getframeinfo(interframe).filename
print "[%s] %s" % (location, message)
return
#now get to work
frameinfo = getframeinfo(frame)
where = frameinfo.function
what = None
caller_call = frameinfo.code_context
# that's the dirty heuristic
first_part = caller_call[0].split('.', 1)[0]
#handle callables
first_part = first_part.split('(', 1)[0]
# let's find the object in locals/globals
what = frame.f_locals.get(first_part, frame.f_globals.get(first_part))
# formatting part
if isclass(what):
what = what.__name__
elif ismethod(what):
#we'll look for im_class
pass
elif isfunction(what):
what = what.__name__
elif what is None:
# * first_part not found in locals/globals
# * class construct
# other cases, probably, should end into this branch
what = frameinfo.filename
else: #object -and some other things?
what = what.__class__.__name__
print "[%s] %s" % (what, message)
class Poc(object):
def repoc(self):
wannaknow("in repoc") and "noop"
class Poc2(object):
@classmethod
def whereami(cls):
"noop" and wannaknow("in whereami")
class Poc3(object):
@staticmethod
def lostcharlie():
wannaknow("in lostcharlie")
def findme():
wannaknow("in findme")
class Wicked(object):
"""
can't catch this one
"""
wannaknow("in class construct!")
p = Poc()
p.repoc()
Poc2.whereami()
Poc3.lostcharlie()
findme()
wannaknow("stray call")
# stripped output:
#=================
# [letgetdirty.py] in class construct!
# [Poc] in repoc
# [Poc2] in whereami
# [Poc3] in lostcharlie
# [findme] in findme
# [letgetdirty.py] stray call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment