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.
type("hi") # <class 'str'> type([]) is list # True
Try it
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.
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
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) == intisFalse, becauseboolis a subclass ofint;isinstance(True, int)isTrue. Preferisinstance()orissubclass()in checks.type(x) is Tis the right comparison when you really want an exact match; useisrather than==.obj.__class__normally gives the same answer, but a proxy object can lie about__class__whiletype()reports the real type.- Classes are objects.
type(int)istype, andtype(type)istypeitself. - Dynamic classes from three arguments are what the
classstatement builds. It is how dataclass-like factories,collections.namedtupleand ORMs create classes, but a normalclassis clearer when names are known. - Metaclasses. Subclass
typeand passmetaclass=...to customize class creation (__new__,__init_subclass__often suffices instead). Callingtype(...)with three arguments honors the most derived metaclass of the bases. - Type hints do not use
type(); see type hints. Thetypestatement (3.12+) defines type aliases and is a different feature. - Calling a type creates an instance:
type(3)("5")is5.