Skip to content

Instantly share code, notes, and snippets.

@andrewgodwin
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewgodwin/f192a20e3b4cf0f5b5d8 to your computer and use it in GitHub Desktop.
Save andrewgodwin/f192a20e3b4cf0f5b5d8 to your computer and use it in GitHub Desktop.
Function Membership Introspection
class MyClass(object):
def a(self):
pass
b = [a]
# Get the reference to a from the list
a = MyClass.b[0]
# How do I get the class a was defined on? Is it even possible?
# On Python 3, I can use __qualname__. This isn't around on Python 2.
@alexsv
Copy link

alexsv commented May 20, 2014

interesting thing, that a in the list is a function, but not an unbound method

~ a
function a at 0x101492de8
~ MyClass.a
unbound method MyClass.a
~ MyClass.b
[function a at 0x101492de8]
~ MyClass.dict['a']
function a at 0x101492de8

@vartec
Copy link

vartec commented May 20, 2014

>>> inspect.ismethod(a)
False
>>> inspect.ismethod(MyClass.b[0])
False

So since it's not a method, there doesn't seem to be any way of getting class it was defined in.

@alexsv
Copy link

alexsv commented May 20, 2014

possible try to play inspect.getinnerframes, inspect.getlineno and parse python code to find class definition :)

@vartec
Copy link

vartec commented May 21, 2014

@alexsv I've tried getting the code and the only thing you get is

    def a(self):
        pass

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment