liveBook · Manning

Type function

As explained in The Quick Python Book, Fourth Edition

The Python type function returns an object's type or creates a new type when called with class-construction arguments.

Python’s built-in type function returns the type of any object. Calling it on 5 produces <class 'int'>; calling it on a list produces <class 'list'>. section 17.1

The result is itself an object: its type is <class 'type'>. Python therefore treats classes and types as objects that can be stored or passed around. section 17.1

Use type alongside related class-inspection tools:

  • Inspect an instance with type(obj) or obj.__class__; both identify the class of the instance. section 17.3
  • Inspect a class with __name__ and __bases__ to find its name and immediate base classes. section 17.3
  • Prefer isinstance for checking whether an object belongs to a class or one of its subclasses, and use issubclass for classes. section 17.3

Inspecting an instance

class A: pass class B(A): pass b = B() type(b) # <class '__main__.B'> b.__class__ # <class '__main__.B'> type(type(b)) # <class 'type'> section 17.3

Capturing a type for validation

class TypedList: def __init__(self, example_element): self.type = type(example_element) x = TypedList('Hello') # x.type is <class 'str'> section 17.8

type(5)
 
<class 'int'>
 
type(['hello', 'goodbye'])
 
<class 'list'>

Compare the values returned by type for an integer and a list. section 17.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains returned type objects, instance inspection, inheritance metadata, and validation use, but does not develop class construction through type.
Examples
Demonstrates integers, lists, user-defined instances, inheritance, and a TypedList that enforces homogeneous elements.
What it assumes
Assumes familiarity with Python objects, classes, instances, and inheritance while reinforcing that classes are objects.
What you can do after
Diagnose object and class relationships, then apply captured types in runtime validation.
How it connects
Connects type to classes, objects, instances, inheritance, __class__, __name__, __bases__, isinstance, and issubclass.

Also explained in

Compare how 3 books explain type function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.