How do I check if an object is an instance of a given class or of a subclass of it?

Use the built-in function isinstance.

if isinstance(obj, MyClass):
     print "obj is my object"

You can check if an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. isinstance(obj, (class1, class2, …)), and can also check whether an object is one of Python’s built-in types. Examples:

if isinstance(obj, str):
     print repr(obj), "is an 8-bit string"

if isinstance(obj, basestring):
     print repr(obj), "is some kind of string"

if isinstance(obj, (int, long, float, complex)):
     print obj, "is a built-in number type"

if isinstance(obj, (tuple, list, dict, set)):
     print "object is a built-in container type"

Note that most programs do not use isinstance on user-defined classes very often. If you are developing the classes yourself, a more proper object-oriented style is to define methods on the classes that encapsulate a particular behaviour, instead of checking the object’s class and doing a different thing based on what class it is. For example, if you have a function that does something:

def search(obj):
    if isinstance(obj, Mailbox):
        print "search a mailbox"
    elif isinstance(obj, Document):
        print "search a document"
    else:
        print "unknown object"

A better approach is to define a search() method on all the classes and just call it:

class Mailbox:
    def search(self):
        print "search a mailbox"

class Document:
    def search(self):
        print "search a document"

obj.search()

CATEGORY: programming

 

Comment:

The common question is "How do I test for the type of an object?". This question should be answared with "See 'How do I check if an object is an instance of a given class or of a subclass of it?'". An opinion that must be here (from Calvin Spealman @ c.l.py): """ In nearly all cases where someone asks this question, the situation turns out to not call for it at all. Usually you simply aren't thinking in the language you are using properly. You should usually know what you are dealing with. If you don't, then either the different types of objects you might have should be interchangable or you should create a situation where you dont have such an ambiguality. Perhaps you could change the design such that you always have a list, even if its just a list of a single string. """ http://groups.google.com/group/comp.lang.python/msg/4ea22c5f4534cbf5

Posted by Eduardo de Oliveira Padoan (2006-12-01)

A Django site. this page was rendered by a django application in 0.04s 2009-01-09 04:07:53.944698. hosted by webfaction.