Python Object System - Part I

31 Jan 2016

object is the most base type of all objects in Python. That means everything in Python is an object (isinstance(anything, object) is always true):

In [42]: help(object)

Help on class object in module __builtin__:

class object
 |  The most base type

And, all values in Python have a type:

In [19]: x = 42

In [20]: type(42)
Out[20]: int

In [21]: s = 'SSS'

In [22]: type(s)
Out[22]: str

In [30]: l = [1, 2 ,3]

In [31]: type(l)
Out[31]: list

From the examples above, we can easily see that the class is the type of instances created. Or, in other words, the class is a callable that creates instances.

However, classes are values too; in fact, classes are ordinary objects in Python that can be passed around just like any other objects. This characteristic earned itself the nickname: first-class objects. Please note that classes in C++ are not first-class objects, but the instances of classes are. This really makes the statement - everything in Python is an object - even more true.

Since classes are values too, or, in other words, classes are instances of some type(s), what is the ‘type’ of classes (let’s focus only on builtin classes now …)? In the begining of this post, I mentioned that object is the most base type of all objects - does that mean the type of classes is also object? - Let’s find out:

In [48]: type(int)
Out[48]: type

In [2]: type(list)
Out[2]: type

In [23]: type(object)
Out[23]: type

In [3]: class Spam(object): pass

In [4]: type(Spam)
Out[4]: type

In [5]: isinstance(Spam, type)
Out[5]: True

In [7]: type(type)
Out[7]: type

In [18]: isinstance(type, type)
Out[18]: True

In [6]: isinstance(Spam, object)
Out[6]: True

In [8]: isinstance(type, object)
Out[8]: True

In [9]: isinstance(object, type)
Out[9]: True

What’s going on here? From above, it tells us several things:

  1. All builtin classes are instances of class type, not object
  2. type is its own class; this class creates new type objects
  3. type object is still an instance of object (type is a child of object)

This requires some thought (a brain-twister!), but basically the take-away is: all Python builtin classes are instances of type, including type itself and object. In other words, the ‘base’ type of class/type system in Python is class type.

type is a special and important class, because it is used when defining classes (creating class instances). It is actually a Python MetaClass, which means a class of classes or a type of types. More about this in Part II.