1

I'm trying to inspect source code using the python inspect module. An example of the code I'm inspecting in this case is:

class xxx:

    def __init__(self):
        pass

    def xxxmethod(self):
        pass

I would expect that when I inspect this code and check the type of 'xxxmethod' it would be types.MethodType. As also suggested here, I use this to receive the function element:

found_function = getattr(class_element, method_name, None)

Its type is however types.FunctionType instead of types.MethodType.

When I print the content of the class_element using getmembers(),

('xxxmethod', <function xxxmethod at 0x00000000028EC6C8>)

this is the element in the dictionary.

Why exactly does it behave like this? Did I overlook something?

EDIT: class_element is received from the scope dictionary. Does it have something to do with the fact that this is no instance of the class?

Thanks!

1 Answer 1

2

Python 2 and 3 differ in this respect.

In Python 2 you would have got a:

<type 'instancemethod'>

but which if you printed the method would give:

<unbound method A.m>

In Python 3 you will instead get:

<class 'function'>

Ultimately it is because you are looking up the method on the class.

In Python 2 accessing the method via the class returns what was referred to as unbound method. The concept of unbound methods was done away with in Python 3.

Now if instead you actually created an instance of the class, in Python 2 you will again get:

<type 'instancemethod'>

which if you print it out gives:

<bound method A.m of <__main__.A instance at 0x10ae7ad40>>

and in Python 3:

<class 'method'>

which is the equivalent of instance method from Python 2 and similarly prints out as:

<bound method A.m of <__main__.A object at 0x10063c6d8>>

So yes, it is because you aren't looking up the method on an instance of the class. Further confused by the fact that Python 3 no longer has the concept of unbound methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.