You said that type
is a function. But it isn’t a function – it is a
class!
repr(type) # returns "<class 'type'>"
When called with one argument, it returns the class of the argument. But
when called with three arguments, it creates a new class.
type(obj) -> type of obj
type(name, bases, dict) -> a new type
In Python, classes are objects just like instances 42, “Hello World”,
None, True, etc. Every object has a class:
type(42) # returns the class `int`
Classes are objects too, so they have a class:
type(int) # returns the class `type`
All objects have a class, and classes are no exception. They too have a
class, the class of a class is called the metaclass. The basic metaclass
in Python is type
.
So all built-in classes, like int, list, str, float, etc, are instances
of the metaclass type
:
type(str) # returns the class `type`
isinstance(str, type) # returns True
The same applies to classes you create yourself:
class MyClass:
pass
isinstance(MyClass, type) # returns True
So far, things are fairly simple:
-
objects are instances of a class;
-
classes are objects too;
-
so classes are instances of a class, the metaclass;
-
the standard metaclass is type
.
But type
is special because:
-
type
is an object, so it must be an instance of a class;
-
type
is also a class, so it too must have a metaclass.
And that metaclass must have a meta-metaclass, and that meta-metaclass
must have a meta-meta-metaclass, and so on forever. Obviously this is
silly. The chain must stop somewhere. It stops at type
, which is
special: it is it’s own metaclass. The Python interpreter has to create
type and object (the base class of all objects) specially:
-
object is a class, so it is an instance of type:
isinstance(object, type) → True
-
type is an object, so it is an instance of object:
isinstance(type, object) → True
Because type
is a class:
-
it must be an instance of itself: isinstance(type, type) → True
-
the type of type
is type
: type(type) → type
-
because type
is a class, it must be a subclass of object:
issubclass(type, object) → True