Skip to content

Instantly share code, notes, and snippets.

@abrookins
Created February 22, 2012 21:00
Show Gist options
  • Save abrookins/1887230 to your computer and use it in GitHub Desktop.
Save abrookins/1887230 to your computer and use it in GitHub Desktop.
Get the name of the class of a decorated method in Python 2.7
def print_class_name(fn):
"""
A decorator that prints the name of the class of a bound function (IE, a method).
NOTE: This MUST be the first decorator applied to the function! E.g.:
@another_decorator
@yet_another_decorator
@print_class_name
def my_fn(stuff):
pass
This is because decorators replace the wrapped function's signature.
"""
@wraps(fn)
def inner(*args, **kwargs):
args_map = {}
if args or kwargs:
args_map = inspect.getcallargs(fn, *args, **kwargs)
# We assume that if an argument named `self` exists for the wrapped
# function, it is bound to a class, and we can get the name of the class
# from the 'self' argument.
if 'self' in args_map:
cls = args_map['self'].__class__
print 'Function bound to class %s' % cls.__name__
else:
print 'Unbound function!'
return fn(*args, **kwargs)
return inner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment