Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 
like image 277
quano Avatar asked Aug 11 '09 12:08

quano


People also ask

How do I know if a class is instance of a variable?

Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .

Why Isinstance is used in Python?

Definition and Usage. The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.

How do you check if an object is of a certain class Python?

In Python, the built-in functions type() and isinstance() help you determine the type of an object. type(object) – Returns a string representation of the object's type. isinstance(object, class) – Returns a Boolean True if the object is an instance of the class, and False otherwise.


1 Answers

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)   
like image 198
Tom Dunham Avatar answered Oct 13 '22 22:10

Tom Dunham