Created
July 22, 2009 23:44
-
-
Save andreyvit/152398 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This code is a part of CrashKit, a web-based crash collection and analysis software | |
# (http://crashkitapp.appspot.com). Please consider it to be in public domain. | |
def get_class_name(frame): | |
"""Guesses a class name to show in a stack trace for the given frame, | |
based on the attributes of the first argument of the frame's function.""" | |
code = frame.f_code | |
fname = code.co_name | |
if code.co_argcount > 0: | |
first = code.co_varnames[0] | |
self = frame.f_locals[first] | |
for key in dir(self): | |
try: attr = getattr(self, key, None) | |
except Exception: attr = None | |
if attr is not None: | |
name = get_method_name_for_code_object(self, attr, code) | |
if name: return name | |
return None | |
def get_method_name_for_code_object(self, possible_func, code, depth = 0): | |
"""Given an object and a value of an attribute of that object, | |
determines if the value is a bound method or a function implemented by the given code object, | |
possibly decorated with one or more decorators. | |
If it is, returns a best guess on the name of the class the function is bound to. | |
Otherwise, returns None.""" | |
if depth > 5: return None | |
try: | |
if code == possible_func.func_code: | |
if isinstance(self, ClassType) or isinstance(self, type): | |
return self.__name__ | |
else: | |
return self.__class__.__name__ | |
except AttributeError: pass | |
try: | |
if code == possible_func.im_func.func_code: | |
if isinstance(self, ClassType) or isinstance(self, type): | |
return self.__name__ | |
else: | |
return possible_func.im_class.__name__ | |
except AttributeError: pass | |
try: | |
if possible_func.func_closure is not None: | |
for cell in possible_func.func_closure: | |
try: | |
name = get_method_name_for_code_object(self, cell.cell_contents, code, depth + 1) | |
if name: return name | |
except AttributeError: pass | |
except AttributeError: pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment