Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

Python : Assert that variable is instance method?

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...