Sunday, November 18, 2012

isinstance() and type() functions in Python

One of python's great strengths is introspection, the ability to examine an object's or module's properties at run-time. In this post we'll touch on two inbuilt functions that are used for the purpose.

The type() function returns the type of the object passed to it:

type("a string") # <type 'str'>
type(['a', 'list']) # <type 'list'>

isinstance() accepts as its parameters an object and class, and returns True if the object is an instance of the class:

isinstance("a string", str)  # True
isinstance("a string", list) # False

If you're ever need to choose between the two, isinstance() is the better one because it factors in inheritance. Say, for example, you subclass the string type:

class MyString(str):
    pass

mystring = MyString()

The types module defines names for all the inbuilt types. We'll import it and use it for comparison.

import types

type("a string") == types.StringType # True
type(mystring) == types.StringType # False

mystring belongs to a subclass of the inbuilt string type (str) and in many cases you'll want treat it as a string. isinstance() will allow you to determine if you can treat it like a string without having to know its exact type.

isinstance("a string", str) # True
isinstance(mystring, str) # True

in_lowercase = mystring.lower()
...

No comments:

Post a Comment