Home > Articles

Types and Objects

  • Print
  • + Share This
This chapter is from the book

Object Identity and Type

The built-in function id() returns the identity of an object as an integer. This integer usually corresponds to the object’s location in memory, although this is specific to the Python implementation and the platform being used. The is operator compares the identity of two objects. The built-in function type() returns the type of an object. For example:

# Compare two objects
def compare(a,b):
  print ‘The identity of a is ‘, id(a)
  print ‘The identity of b is ‘, id(b)
  if a is b:
    print ‘a and b are the same object’
  if a == b:
    print ‘a and b have the same value’
  if type(a) is type(b):
    print ‘a and b have the same type’

The type of an object is itself an object. This type object is uniquely defined and is always the same for all instances of a given type. Therefore, the type can be compared using the is operator. All type objects are assigned names that can be used to perform type checking. Most of these names are built-ins, such as list, dict, and file. For example:

if type(s) is list:
  print ‘Is a list’

if type(f) is file:
  print ‘Is a file’

However, some type names are only available in the types module. For example:

import types
if type(s) is types.NoneType:
  print "is None"

Because types can be specialized by defining classes, a better way to check types is to use the built-in isinstance(object, type) function. For example:

if isinstance(s,list):
  print ‘Is a list’

if isinstance(f,file):
  print ‘Is a file’

if isinstance(n,types.NoneType):
  print "is None"

The isinstance() function also works with user-defined classes. Therefore, it is a generic, and preferred, way to check the type of any Python object.

  • + Share This
  • 🔖 Save To Your Account