Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `type` really a function, or not?

First, I'm sorry if I'm asking something dumb, because I'm new to Python...
I was reading http://docs.python.org/3.1/reference/datamodel.html#objects-values-and-types and saw that phrase:

The type() function returns an object’s type (which is an object itself)

Of course, I decided to check this:

>>> def someFunction(x):
...     return x * x
...     
>>> type(someFunction)
<class 'function'>
>>> type(type)
<class 'type'>

So, looks like functions have the function type, but then why type function has a different type if it is a function? Or the docs are lying and it's not really a function?

like image 555
Display Name Avatar asked Oct 23 '25 04:10

Display Name


2 Answers

Yes, type is a function, but it is implemented in C.

It also has to be it's own type, otherwise you could not do:

>>> def foo(): pass
... 
>>> type(foo)
<type 'function'>
>>> type(type)
<type 'type'>
>>> isinstance(type(foo), type)
True

e.g. you could not test if a type is a type, if type's type was not type but function. With me still?

Technically speaking, type is a callable, and has two related roles to play. It is a metaclass (a class factory) and the base for all types in Python, and when called it produces a type instance (<type 'function'> is an instance of the type type).

The same applies to all types (including classes); call them and they produce a new instance of the given type.

like image 131
Martijn Pieters Avatar answered Oct 26 '25 01:10

Martijn Pieters


  1. Note that in Python anything is object. An object may be callable, i.e. work as function.
  2. type is a built-in function, i.e. object of type that you can call as function. You can call it with one argument to get the type of an object. But there is also another use case.
  3. type is a metaclass, this means it is a type itself and can create classes (which are objects too).
  4. All classes (and also metaclasses) are callable, this is one more reason why type is function. You can call it with three arguments to create a class.
  5. type is basic built-in metaclass. So it is a base of anything in Python. Because type is on top of hierarchy of types, type(type) returns type, i.e. type is type of itself.

You also may wonder:

  • What is a metaclass in Python?
  • What is a “callable” in Python?
like image 44
raacer Avatar answered Oct 26 '25 01:10

raacer