All data in a Python program is held in objects, including numbers, functions, classes and modules. This page covers what an object is, the types the language defines, and the special methods that let a class take part in Python's syntax. It follows chapter 3 of the Language Reference.
Objects, identity, type and value
Every object has three things (3.1):
| Property | Tested by | Can it change? |
|---|---|---|
| Identity | x is y, id(x) | Never. In CPython id(x) is the object's memory address |
| Type | type(x), isinstance(x, T) | Unchangeable in general |
| Value | x == y | Only for mutable objects |
c = []
d = []
c is d # False: two different lists
e = c
e is c # True: two names, one list
c == d # True: equal values
Mutable and immutable objects
Objects whose value can change are mutable, such as lists and dictionaries. Others are immutable, such as numbers, strings and tuples. A tuple cannot change which objects it refers to, but an object it refers to may itself be mutable.
Equal immutable objects may or may not be the same object: after a = 1; b =
1, a is b depends on the implementation. For mutable objects it
is guaranteed: after c = []; d = [] the two are different lists.
Lifetime
An object is never destroyed explicitly. It may be reclaimed once it becomes
unreachable. How and when is up to the implementation: CPython uses reference
counting with a collector for cycles, but programs should not depend on it. Close
files and other resources with a
with statement.
The standard type hierarchy
These are the types built into the language (3.2):
| Category | Types | Notes |
|---|---|---|
| Singletons | None, NotImplemented, Ellipsis | One object each. See Types |
| Integral numbers | int, bool | bool is a subtype of int |
| Real numbers | float | Double precision in CPython |
| Complex numbers | complex | A pair of floats |
| Immutable sequences | str, tuple, bytes | Also range |
| Mutable sequences | list, bytearray | |
| Set types | set, frozenset | Items must be hashable |
| Mappings | dict, frozendict | frozendict since 3.15 |
| Callable types | User-defined functions, methods, generator, coroutine and asynchronous generator functions, built-in functions and methods, classes, instances with __call__ | See Functions |
| Modules | types.ModuleType | See Modules and packages |
| Custom classes | Created by a class statement | See Classes |
| Class instances | Created by calling a class | |
| I/O objects | File objects from open() | Also sys.stdin, sys.stdout, sys.stderr |
| Internal types | Code, frame, traceback, slice, static method and class method objects | Used by the interpreter |
Types describes the behaviour of the built-in numbers, sequences, mappings and sets.
Special methods
A class takes part in Python's syntax by defining methods with special names, written
with double underscores (3.3). x[i] runs
type(x).__getitem__(x, i), and len(x) runs
type(x).__len__(x). Setting a special method to None says the
operation is not available.
How special methods are found
When Python calls a special method implicitly, it looks it up on the object's type, not on the instance (3.3.13):
class C:
pass
c = C()
c.__len__ = lambda: 5
len(c) # TypeError: object of type 'C' has no len()
Basic customisation
| Method | Called by | Rules |
|---|---|---|
__new__(cls, ...) | Creating an instance | A static method, even without a decorator. Returns the new object |
__init__(self, ...) | After __new__ | Sets up the instance. Must return None |
__del__(self) | When the object is about to be destroyed | A finaliser, which may never run. Not called by del x directly |
__repr__(self) | repr(x) | Should be a valid expression for the object where possible |
__str__(self) | str(x), print(x), format(x) | Falls back to __repr__ |
__bytes__(self) | bytes(x) | Must return bytes |
__format__(self, spec) | format(x, spec), f-strings, str.format | Must return a str |
__lt__, __le__, __eq__, __ne__, __gt__, __ge__ | <, <=, ==, !=, >, >= | Rich comparison. May return any value, or NotImplemented |
__hash__(self) | hash(x), dictionary keys, set items | Must be equal for equal objects |
__bool__(self) | bool(x) and truth tests | Must return a bool. Falls back to __len__, then to true |
- Comparison. The default
__eq__compares identity, and__ne__inverts__eq__by default. There are no reflected comparison methods:x < ytriesx.__lt__(y), theny.__gt__(x). If the right operand's type is a subclass of the left's, its method runs first. - Hashing. A class that defines
__eq__without__hash__has its__hash__set toNone, so its instances cannot be dictionary keys.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
def __add__(self, other):
if not isinstance(other, Point):
return NotImplemented
return Point(self.x + other.x, self.y + other.y)
Attribute access
| Method | Called by |
|---|---|
__getattr__(self, name) | Only when normal lookup fails with AttributeError |
__getattribute__(self, name) | Every attribute read on the instance |
__setattr__(self, name, value) | x.name = value |
__delattr__(self, name) | del x.name |
__dir__(self) | dir(x) |
A module can define __getattr__ and __dir__ as ordinary
functions to customise access to its own attributes (PEP 562, Python 3.7).
Descriptors and
__slots__ are on the Classes
page.
Containers
| Method | Called by |
|---|---|
__len__(self) | len(x); must be 0 or more |
__length_hint__(self) | An estimate of length for preallocation |
__getitem__(self, key) | x[key] |
__setitem__(self, key, value) | x[key] = value |
__delitem__(self, key) | del x[key] |
__missing__(self, key) | By dict.__getitem__, for a subclass, when a key is absent |
__iter__(self) | iter(x), for loops |
__reversed__(self) | reversed(x) |
__contains__(self, item) | item in x |
A slice such as x[1:3] reaches __getitem__ as a
slice object. If a class has no __iter__,
iter() falls back to calling __getitem__ with 0, 1, 2 and
so on until IndexError. If it has no __contains__,
in iterates.
Numeric methods
Each binary operator has a method, a reflected form tried with the operands swapped, and an in-place form for augmented assignment (3.3.8):
| Operator | Method | Reflected | In place |
|---|---|---|---|
+ | __add__ | __radd__ | __iadd__ |
- | __sub__ | __rsub__ | __isub__ |
* | __mul__ | __rmul__ | __imul__ |
@ | __matmul__ | __rmatmul__ | __imatmul__ |
/ | __truediv__ | __rtruediv__ | __itruediv__ |
// | __floordiv__ | __rfloordiv__ | __ifloordiv__ |
% | __mod__ | __rmod__ | __imod__ |
divmod() | __divmod__ | __rdivmod__ | none |
**, pow() | __pow__ | __rpow__ | __ipow__ |
<< | __lshift__ | __rlshift__ | __ilshift__ |
>> | __rshift__ | __rrshift__ | __irshift__ |
& | __and__ | __rand__ | __iand__ |
^ | __xor__ | __rxor__ | __ixor__ |
| | __or__ | __ror__ | __ior__ |
| Kind | Methods |
|---|---|
| Unary | __neg__ __pos__ __abs__ __invert__ |
| Conversion | __complex__ __int__ __float__ __index__ |
| Rounding | __round__ __trunc__ __floor__ __ceil__ |
For x + y:
- If the type of
yis a subclass of the type ofxand overrides__radd__,y.__radd__(x)is tried first. - Otherwise
x.__add__(y)is tried. If it is missing or returnsNotImplemented,y.__radd__(x)is tried. - If nothing works,
TypeErroris raised.
If both operands have the same type, the reflected method is not tried.
x += y tries x.__iadd__(y) first and falls back to the rule
above. __index__ gives an object an exact integer, which lets it serve
as a list index or in hex(). Since Python 3.14, int() no
longer delegates to __trunc__.
Other protocols
| Method | Used for | See |
|---|---|---|
__call__(self, ...) | Calling an instance like a function | Functions |
__enter__, __exit__ | The with statement | Statements |
__match_args__ | Positional class patterns | Match |
__instancecheck__, __subclasscheck__ | isinstance and issubclass, defined on the metaclass | Classes |
__class_getitem__ | C[int] on a class, for generics | Type hints |
__buffer__, __release_buffer__ | The buffer protocol from Python code (PEP 688) | |
__await__ | await | Generators and async |
__aiter__, __anext__ | async for | Generators and async |
__aenter__, __aexit__ | async with | Generators and async |