A Quick Refresher · Lecture 01 · 10 min
The Python Type Hierarchy
A map of the built-in types you'll meet throughout these four parts (numbers, collections, callables and singletons) and how Python itself groups them.
Why families?
Python has many built-in types, and they aren’t a flat list. They fall into families that share behavior: every sequence can be indexed and sliced, every mapping looks values up by key, every callable can be called with (). Knowing which family a type belongs to tells you most of what you can do with it.
This lesson walks through the four families the rest of the material explores in depth: numbers, collections, callables and singletons.
Numbers
Numbers split into integral numbers (whole numbers) and non-integral ones.
int: integers of any size. Python integers never overflow.bool:TrueandFalse. Surprisingly,boolis a subclass ofint:Truebehaves like1andFalselike0.float: real numbers stored in binary (a Cdoubleunder the hood), so most decimal fractions are approximations.complex: numbers with a real and an imaginary part, like3+4j.Decimal(moduledecimal): decimal arithmetic with precision you control, useful for money.Fraction(modulefractions): exact rational numbers such as 1/3.
from decimal import Decimal
from fractions import Fraction
print(isinstance(True, int), True + True)
print(0.1 + 0.2 == 0.3) # binary floats are approximate
print(Decimal('0.1') + Decimal('0.2') == Decimal('0.3')) # decimal arithmetic is exact here
print(Fraction(1, 3) * 3 == 1) # 1/3 is exact as a FractionWhy have so many? A float can’t store one third exactly: 0.333… would need infinitely many digits. If you need 1/3 + 1/3 + 1/3 to be exactly 1, you need Fraction.
Python also describes these families formally in the numbers module, so you can ask about a family rather than a specific type:
import numbers
for value in (7, True, 2.5, 3+4j, Fraction(1, 3), Decimal('1.5')):
print(f'{value!r:>22} Integral={isinstance(value, numbers.Integral)!s:5} '
f'Real={isinstance(value, numbers.Real)!s:5} Number={isinstance(value, numbers.Number)}')Notice that Decimal is a Number but deliberately not a Real: it doesn’t mix freely with floats. Part 1 · Section 04 covers all of these types in detail.
Collections
Collections hold other objects. There are three big groups:
- Sequences: ordered and indexable by position.
listis mutable;tupleandstrare immutable. - Sets: unordered collections of unique items.
setis mutable;frozensetis its immutable twin. - Mappings: look up values by key. The built-in mapping is
dict.
Sets and dictionaries are closely related: both are hash tables. A set is essentially a dictionary that only stores keys. That’s why both need their elements or keys to be hashable, and why both offer very fast membership tests. Part 3 is all about them.
The collections.abc module defines these families too, which is handy for checking what an object supports:
from collections.abc import Sequence, MutableSequence, Set, MutableSet, Mapping
samples = {'list': [1, 2], 'tuple': (1, 2), 'str': 'ab',
'set': {1, 2}, 'frozenset': frozenset({1, 2}), 'dict': {'a': 1}}
for name, obj in samples.items():
kinds = [abc.__name__ for abc in (Sequence, MutableSequence, Set, MutableSet, Mapping)
if isinstance(obj, abc)]
print(f'{name:>9}: {", ".join(kinds)}')Callables
A callable is anything you can call with parentheses. This family is defined by behavior, and it’s bigger than you might expect:
- user-defined functions (
defandlambda) - generator functions (functions that
yield), which you’ll study in Part 2. Calling one returns a generator object, which is iterable but not itself callable - classes: calling a class creates an instance
- instance methods: functions bound to an object
- class instances that define
__call__ - built-in functions like
lenandopen, and built-in methods likelist.append
The built-in callable() tells you whether an object can be called:
def greet(name):
return f'Hello, {name}'
def countdown(n):
while n > 0:
yield n
n -= 1
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x): # makes *instances* callable
return x * self.factor
double = Multiplier(2)
things = [greet, countdown, Multiplier, double, double.__call__, len, [].append, 42, 'text']
for obj in things:
print(f'{type(obj).__name__:>26} callable: {callable(obj)}')
print(double(21))Multiplier (the class) and double (an instance) are both callable, but for different reasons: calling the class builds an object, and calling the instance runs __call__. Part 4 explains how this works.
Singletons
A few objects exist exactly once in a running program:
None: “no value”. Every reference toNonepoints to the same object.NotImplemented: a special value that operator methods like__eq__or__add__return to say “I don’t know how to handle that type”. You’ll meet it in Part 4.Ellipsis, also written...: used in slicing by some libraries, and often as a placeholder.
a = None
b = None
print(a is b, type(None).__name__)
print(... is Ellipsis, type(...).__name__)
print(type(NotImplemented).__name__)Because each exists only once, you test for them with is: if x is None:.
The real hierarchy is larger: bytes and bytearray, range, memoryview, modules, code objects, and more. This lesson covers the types studied in depth; the others appear where they’re useful.
Key takeaways
- Numbers are integral (
int,bool) or non-integral (float,complex,Decimal,Fraction).boolis a subclass ofint. - Collections are sequences (mutable
list; immutabletuple,str), sets (set,frozenset) and mappings (dict). Sets and dicts are both hash tables. - Callables are anything you can call: functions (including generator functions), classes, methods, built-ins, and instances with
__call__. None,NotImplementedandEllipsisare singletons, so compare them withis.- The
numbersandcollections.abcmodules let you test which family an object belongs to.