Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python type() function

Reference for Python type(): get an object's type, create classes dynamically with three arguments, and how type() differs from isinstance() and metaclasses.

type() has two jobs. With one argument it returns the exact type (class) of an object: type(3) is <class 'int'>. With three arguments it creates a brand-new class at runtime. In fact, type is the default metaclass: every ordinary class is an instance of it.

For checking types in everyday code, isinstance() is usually better, because it respects inheritance. Use the one-argument type() when you need the exact class, for example to print its name or look up a handler.

Python
type("hi")        # <class 'str'>
type([]) is list  # True

Try it

Python Finding the type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Creating classes with three arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
type(object)
type(name, bases, dict, **kwds)
Name Description
object Any value; its exact type is returned.
name A string used as the new class's __name__.
bases A tuple of base classes (may be empty).
dict A dictionary that becomes the class namespace: methods, attributes, __doc__.

Return value: the type of object, or a new class.

Raises: TypeError for two arguments or arguments of the wrong kinds, or a conflicting base-class layout.

Usage notes

  • type(x) ignores inheritance. type(True) == int is False, because bool is a subclass of int; isinstance(True, int) is True. Prefer isinstance() or issubclass() in checks.
  • type(x) is T is the right comparison when you really want an exact match; use is rather than ==.
  • obj.__class__ normally gives the same answer, but a proxy object can lie about __class__ while type() reports the real type.
  • Classes are objects. type(int) is type, and type(type) is type itself.
  • Dynamic classes from three arguments are what the class statement builds. It is how dataclass-like factories, collections.namedtuple and ORMs create classes, but a normal class is clearer when names are known.
  • Metaclasses. Subclass type and pass metaclass=... to customize class creation (__new__, __init_subclass__ often suffices instead). Calling type(...) with three arguments honors the most derived metaclass of the bases.
  • Type hints do not use type(); see type hints. The type statement (3.12+) defines type aliases and is a different feature.
  • Calling a type creates an instance: type(3)("5") is 5.