What is the purpose of type() and the types module and what is a type?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jun 27 05:03:10 EDT 2013


On Thu, 27 Jun 2013 01:34:34 -0700, Russel Walker wrote:

> The type() builtin according to python docs, returns a "type object".
> http://docs.python.org/2/library/types.html
> 
> And in this module is bunch of what I assume are "type objects". Is this
> correct? http://docs.python.org/2/library/functions.html#type
> 
> And type(), aside from being used in as an alternative to a class
> statement to create a new type, really just returns the object class,
> doesn't it?

type() does two things:

- with a single argument, it returns the actual type of an object;

- with three arguments, it creates new types.

For example, `type(42)` returns int, and type([]) returns list. Not the 
*strings* "int" and "list", but the actual int object and list object.

py> x = 42
py> type(x)("23")
23


The three argument form of type() creates new types, also known as 
classes. The class statement is just syntactic sugar, under the hood it 
calls type.

(Note: in Python 2 there is a slight complication due to the existence of 
so-called "old-style classes", also known as "classic classes". They are 
a bit of a special case, but otherwise don't really make any difference 
to what I'm saying.)

For example, the following:

class Spam(object):
    a = 42
    def method(self, x):
        return self.a + x


is syntactic sugar for the much longer:


def method(self, x):
    return self.a + x

d = {'method': method, 'a': 42}
Spam = type('Spam', (object,), d)
del d, method


(more or less, there may be slight differences).


> If type() didn't exist would it be much more of a matter than the
> following?:
> 
> 
> def type(x):
>     return x.__class__


That only covers the one-argument form of type(). The three-argument form 
is fundamental to Python's workings, Python cannot operate without it, or 
something like it.


> What is the purpose of type()?
> What exactly is a "type object"? Is it a "class"? What is the purpose of
> the types module?

"Type" is a synonym for "class". (To be precise, "new-style class" only, 
classic classes are different, but the precise difference is no longer 
important, and goes away in Python 3.)

The types module is just a collection of useful names for built-in types 
that otherwise don't exist in the default namespace. E.g. functions are 
objects, and have a type, but that type is not available by default:

py> FunctionType
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'FunctionType' is not defined


You need to import it first:

py> from types import FunctionType
py> FunctionType
<type 'function'>




-- 
Steven



More information about the Python-list mailing list