Python type builtin function
last modified November 30, 2026 Python 3.15
In this article we describe the built-in type function:
its one-argument form, which returns the type of an object, and its
three-argument form, which creates a new class.
Using the one-argument form for type checks, comparisons, and
dispatching is covered in Python type
function. This article focuses on what type is and on
creating classes at run time.
The function has two signatures:
type(object) type(name, bases, namespace, **kwargs)
Strictly speaking, type is not a function but a class; we
come back to this at the end of the article.
The one-argument form
With one argument, type returns the class of the object.
class User:
pass
values = [7, 'abc', [], User(), User, len, type]
for value in values:
print(type(value))
The program prints the types of values, a class, a built-in function,
and type itself.
values = [7, 'abc', [], User(), User, len, type]
An instance of User has the type
__main__.User, where __main__ is the module
in which the class is defined. The class User itself, like
every class, has the type type.
$ python one_argument.py <class 'int'> <class 'str'> <class 'list'> <class '__main__.User'> <class 'type'> <class 'builtin_function_or_method'> <class 'type'>
type and __class__
Every object also has a __class__ attribute. Usually it
refers to the same class as type(obj), but a class can
override it, while type always reports the real class.
class Fake:
@property
def __class__(self):
return int
f = Fake()
print(type(f))
print(f.__class__)
print(isinstance(f, int), isinstance(f, Fake))
print(type(f) is int)
The Fake class claims to be an int.
@property
def __class__(self):
return int
The property returns int for the __class__
attribute.
print(isinstance(f, int), isinstance(f, Fake)) print(type(f) is int)
The isinstance function also consults
__class__, so the object passes as both an
int and a Fake. The type
function cannot be fooled. Proxy objects and mocks in tests use this
technique to stand in for other objects.
$ python class_attribute.py <class '__main__.Fake'> <class 'int'> True True False
Creating a class with three arguments
With three arguments, type creates a new class. The
arguments are the class name, a tuple of base classes, and a
dictionary with the class attributes.
class Point:
x = 0
y = 0
Point2 = type('Point2', (), {'x': 0, 'y': 0})
print(Point, Point2)
print(Point2.__name__, Point2.__bases__)
print(Point2.x, Point2.y)
p = Point2()
p.x = 4
print(p.x, p.y, type(p))
The program defines the same class twice: once with a
class statement and once with type.
Point2 = type('Point2', (), {'x': 0, 'y': 0})
The empty tuple means no explicit base class; as with a
class statement, the class then derives from
object. The dictionary becomes the namespace of the class.
p = Point2() p.x = 4
The new class is an ordinary class. We create an instance and set an instance attribute.
$ python three_arguments.py <class '__main__.Point'> <class '__main__.Point2'> Point2 (<class 'object'>,) 0 0 4 0 <class '__main__.Point2'>
Methods and base classes
Functions in the namespace dictionary become methods, and the bases tuple sets the parent classes.
class Shape:
def describe(self):
return f'{type(self).__name__} with area {self.area():.2f}'
def init(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def to_string(self):
return f'Rectangle({self.width}, {self.height})'
Rectangle = type('Rectangle', (Shape,), {
'__init__': init,
'area': area,
'__repr__': to_string,
'sides': 4,
})
r = Rectangle(3, 2.5)
print(r)
print(r.describe())
print(Rectangle.sides, Rectangle.__mro__)
We create a Rectangle class derived from
Shape.
def init(self, width, height):
self.width = width
self.height = height
The methods are written as plain functions with a self
parameter. Their names do not matter; the dictionary keys decide the
method names.
Rectangle = type('Rectangle', (Shape,), {
'__init__': init,
'area': area,
'__repr__': to_string,
'sides': 4,
})
The init function becomes the constructor and
to_string the __repr__ method. The
describe method is inherited from Shape, and
it calls area, which only the subclass defines.
$ python methods.py Rectangle(3, 2.5) Rectangle with area 7.50 4 (<class '__main__.Rectangle'>, <class '__main__.Shape'>, <class 'object'>)
Generating classes from data
The three-argument form is useful when the classes are not known while writing the code, or when many similar classes would be repetitive. In the next example we create exception classes from a dictionary of HTTP status codes.
class APIError(Exception):
code = 500
codes = {'BadRequest': 400, 'Forbidden': 403, 'NotFound': 404}
errors = {}
for name, code in codes.items():
errors[name] = type(name, (APIError,), {'code': code})
def fetch(path):
if path == '/admin':
raise errors['Forbidden'](path)
raise errors['NotFound'](path)
for path in ['/admin', '/missing']:
try:
fetch(path)
except APIError as e:
print(type(e).__name__, e.code, e)
All generated exceptions derive from APIError.
for name, code in codes.items():
errors[name] = type(name, (APIError,), {'code': code})
Each class gets its name and its own code class
attribute. We keep the classes in a dictionary.
except APIError as e:
print(type(e).__name__, e.code, e)
The generated classes are subclasses of APIError, so one
except clause catches them all.
$ python error_classes.py Forbidden 403 /admin NotFound 404 /missing
Class names
The first argument sets the name stored in the class. It is unrelated to the variable the class is assigned to.
def make_class(name):
return type(name, (), {'__doc__': f'The {name} class.'})
Animal = make_class('Animal')
Pet = make_class('Animal')
print(Animal.__name__, Animal.__qualname__, Animal.__module__)
print(Animal.__doc__)
print(Pet.__name__, Pet is Animal)
print(isinstance(Pet(), Animal))
The make_class function is a small class factory.
return type(name, (), {'__doc__': f'The {name} class.'})
The __doc__ key sets the documentation string.
print(Animal.__name__, Animal.__qualname__, Animal.__module__)
The __qualname__ attribute is the same as the name, even
though the class is created inside a function. The
__module__ attribute is taken from the module that calls
type.
Pet = make_class('Animal')
...
print(Pet.__name__, Pet is Animal)
print(isinstance(Pet(), Animal))
Each call creates a new class. The two classes have the same name but are not related.
$ python names.py Animal Animal __main__ The Animal class. Animal False False
Class keywords
Extra keyword arguments to type are passed on in the same
way as keywords in a class statement header, for example to
the __init_subclass__ hook of a base class.
class Plugin:
registry = {}
def __init_subclass__(cls, name, **kwargs):
super().__init_subclass__(**kwargs)
Plugin.registry[name] = cls
class CsvExport(Plugin, name='csv'):
pass
JsonExport = type('JsonExport', (Plugin,), {}, name='json')
print(Plugin.registry)
The Plugin base class registers each subclass under a
name.
class CsvExport(Plugin, name='csv'):
pass
JsonExport = type('JsonExport', (Plugin,), {}, name='json')
Both forms call Plugin.__init_subclass__ with the
name keyword. The hook is explained in
Python __init_subclass__.
$ python keywords.py
{'csv': <class '__main__.CsvExport'>, 'json': <class '__main__.JsonExport'>}
type is a class
The type object is itself a class: it is the class whose
instances are classes. A class of classes is called a metaclass.
import abc
import enum
class User:
pass
print(isinstance(User, type))
print(isinstance(int, type), isinstance(5, type))
print(type(User), type(type))
print(type.__bases__)
print(isinstance(type, object), isinstance(object, type))
print(type(enum.Enum), type(abc.ABC))
print(issubclass(enum.EnumType, type))
The program checks the relations between classes, type,
and object.
print(isinstance(User, type)) print(isinstance(int, type), isinstance(5, type))
Classes are instances of type; ordinary values are not.
print(type(User), type(type)) print(type.__bases__) print(isinstance(type, object), isinstance(object, type))
The type of type is type itself, and
type derives from object. Since
object is a class, it is also an instance of
type. These circular relations are built into the
interpreter.
print(type(enum.Enum), type(abc.ABC)) print(issubclass(enum.EnumType, type))
Some classes in the standard library have their own metaclasses derived
from type. Writing such metaclasses is covered in
Python metaclasses.
$ python type_is_class.py True True False <class 'type'> <class 'type'> (<class 'object'>,) True True <class 'enum.EnumType'> <class 'abc.ABCMeta'> True
Wrong number of arguments
The function accepts one or three positional arguments.
Point = type('Point', ())
With two arguments, type raises a TypeError.
The namespace dictionary is required even when it is empty.
$ python wrong_args.py
Traceback (most recent call last):
File "/home/user/python/wrong_args.py", line 1, in <module>
Point = type('Point', ())
TypeError: type() takes 1 or 3 arguments
Source
type, Metaclasses, Dynamic type creation
In this article we have used the one-argument form of
type, compared it with __class__, created
classes with the three-argument form, added methods and base classes,
generated exception classes from data, looked at the names of dynamic
classes, passed class keywords, and seen that type is the
class of all classes. See also
Python type function,
Python metaclasses, and
Python isinstance builtin
function.
Author
List all Python tutorials.