type(type) is an object, not an instance

Michele Simionato mis6 at pitt.edu
Wed Mar 19 08:32:57 EST 2003


Sip <sip at email.ee> wrote in message news:<mailman.1048039830.32186.python-list at python.org>...
> I don't know if this can be called a bug, but type(type) is the type 
> object, not an instance of it, like type of other types:
> >>> type(type) is type
>  1
> >>> type(int) is int
> 0
> 

I was writing an "Introduction to metaclasses" (I don't know if I will
ever finish it, since I am always discovering new and new things about
them, and also because I am lazy ;).
Here is the beginning, that answer your question:

------------------------------------------------------------------------
  
In the Python object model (inspired from the Smalltalk object model)
classes themselves are objects. 
Now, since objects are instances of classes, that means that classes 
themselves can be seen as instances of special classes called metaclasses.
That seems easy, but actually it gets hairy soon, since by following this 
idea, one can say that metaclasses themselves are classes and therefore 
objects:  this  means than metaclasses can be seen as instances of 
special classes called meta-metaclasses. On the other hand, for the same 
argument, meta-meta-classes can be seen as instances of meta-meta-metaclasses, 
etc. Now, it should be obvious why metaclasses have gained such a reputation 
of brain-exploders ;). However, fortunately, the situation is not so bad in 
practice: the infinite recursion of metaclasses is avoided because there is a 
metaclass that is the "mother of all metaclasses": the built-in metaclass 
type. 'type' has the property of being its own metaclass, therefore the 
recursion stops. 
Consider for instance the following example:

  >>> class C(object): pass # a generic class
  >>> type(C) #gives the metaclass of C
  <type 'type'>
  >>> type(type(C)) #gives the metaclass of type
  <type 'type'>

The recursion stops, since the metaclass of 'type' is 'type'.
One cool consequence of classes being instances of 'type', 
is that since *type* is a subclass of object,

   >>> issubclass(type,object)
   True 

any Python class is not only a subclass of ``object``, but also
an instance of 'object':

   >>> isinstance(C,type)
   True
   >>> isinstance(C,object) 
   True
   >>> issubclass(C,object) 
   True

Notice that 'type' is an instance of itself (!) and therefore of 'object':

  >>> isinstance(type,type) # 'type' is an instance of 'type'
  True
  >>> isinstance(type,object) # therefore 'type' is an instance of 'object'
  True

------------------------------------------------------------------------

For a more formal analysis you can look at the book "Putting metaclasses 
to work" by Forman and Danforth.

                                            Michele




More information about the Python-list mailing list