Skip to content

Instantly share code, notes, and snippets.

@nawie
Forked from techtonik/caller_name.py
Last active May 2, 2018 04:35
Show Gist options
  • Save nawie/d4eb14ab2ced26540be5fdb479657ebe to your computer and use it in GitHub Desktop.
Save nawie/d4eb14ab2ced26540be5fdb479657ebe to your computer and use it in GitHub Desktop.
Python - inspect - Get full caller name (package.module.function)
# Public Domain, i.e. feel free to copy/paste
# Considered a hack in Python 2
import inspect
def caller_name(skip=2):
"""Get a name of a caller in the format module.class.method
`skip` specifies how many levels of stack to skip while getting caller
name. skip=1 means "who calls me", skip=2 "who calls my caller" etc.
An empty string is returned if skipped levels exceed stack height
"""
name = []
limit = iter(xrange(1, skip + 1))
frame = sys._getframe(1)
try:
while frame and next(limit):
frame = frame.f_back
except StopIteration:
parentframe = frame
else:
return ''
name = []
module = inspect.getmodule(parentframe)
# `modname` can be None when frame is executed directly in console
# TODO(techtonik): consider using __main__
if module:
name.append(module.__name__)
# detect classname
if 'self' in parentframe.f_locals:
# I don't know any way to detect call from the object method
# XXX: there seems to be no way to detect static method call - it will
# be just a function call
name.append(parentframe.f_locals['self'].__class__.__name__)
codename = parentframe.f_code.co_name
if codename != '<module>': # top level usually
name.append( codename ) # function or a method
del parentframe
return ".".join(name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment