34

How can one check if a variable is an instance method or not? I'm using python 2.5.

Something like this:

class Test:
    def method(self):
        pass

assert is_instance_method(Test().method)
2
  • 18
    What's wrong with asking here? Commented Aug 11, 2009 at 13:52
  • 3
    Reading the source isn't any help - presumably he's writing some code that needs to know the answer at runtime. Possibly iterating through all attrs on an object, for instance. Commented May 24, 2010 at 16:01

2 Answers 2

55

inspect.ismethod is what you want to find out if you definitely have a method, rather than just something you can call.

import inspect

def foo(): pass

class Test(object):
    def method(self): pass

print inspect.ismethod(foo) # False
print inspect.ismethod(Test) # False
print inspect.ismethod(Test.method) # True
print inspect.ismethod(Test().method) # True

print callable(foo) # True
print callable(Test) # True
print callable(Test.method) # True
print callable(Test().method) # True

callable is true if the argument if the argument is a method, a function (including lambdas), an instance with __call__ or a class.

Methods have different properties than functions (like im_class and im_self). So you want

assert inspect.ismethod(Test().method)  
Sign up to request clarification or add additional context in comments.

3 Comments

+1, inspect is good (and that "defiantly" typo actually reads well;-).
Using Python 3.5, inspect.ismethod(Test.method) returns False.
You should use an instance of test sinse it is an instance method ``` inspect.ismethod(Test().method) ```
8

If you want to know if it is precisely an instance method use the following function. (It considers methods that are defined on a metaclass and accessed on a class class methods, although they could also be considered instance methods)

import types
def is_instance_method(obj):
    """Checks if an object is a bound method on an instance."""
    if not isinstance(obj, types.MethodType):
        return False # Not a method
    if obj.im_self is None:
        return False # Method is not bound
    if issubclass(obj.im_class, type) or obj.im_class is types.ClassType:
        return False # Method is a classmethod
    return True

Usually checking for that is a bad idea. It is more flexible to be able to use any callable() interchangeably with methods.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.