Python Reference ยท Practical Pages
The Python data model
Concept page on the Python data model: everything is an object with an identity, a type and a value, names are references, and special methods hook into syntax.
The data model is Python's description of what a value is and how the language treats it. The short version: every piece of data is an object, every object has an identity, a type and a value, and a variable is just a name that refers to an object. Once you see names as labels attached to objects (not boxes that hold values), assignment, argument passing, copying and mutation bugs all start to make sense.
The data model also defines the special methods (__len__, __add__, __iter__ and friends) that let your own classes work with built-in syntax such as len(x), a + b and for item in x.
a = [1, 2, 3] # create a list object, bind the name a to it b = a # bind a second name to the SAME object
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.
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.
The three parts of an object
| Part | How to look at it | Can it change? |
|---|---|---|
| Identity | id(obj), compared with is |
Never, for the life of the object |
| Type | type(obj) |
Practically never |
| Value | ==, the contents |
Only if the type is mutable |
Identity is "which object is this?", value is "what does it contain?". Use == to compare values and is only for identity checks, almost always x is None. See is and is not.
Names, binding and scope
- Assignment (
x = ...) never copies. It binds a name to an object, replacing any previous binding of that name. - Passing an argument binds the parameter name to the same object the caller passed ("pass by object reference"). Mutating that object inside the function is visible outside; rebinding the parameter is not.
del xremoves the name, not the object. The object is freed when nothing refers to it any more (reference counting, with a cycle collector as backup).- Names live in namespaces (local, enclosing, global, built-in), covered in scope and LEGB.
Types and classes
Everything has a type, and types are themselves objects whose type is type. Built-in types (int, str, list, dict, NoneType...) and your own classes work the same way. Calling a class creates an instance; isinstance(obj, cls) tests membership in a class or its subclasses. Because classes are ordinary objects, you can pass them around, store them in dicts and create them at run time.
Special methods (dunder methods)
Methods named with double underscores are hooks that the interpreter calls for you. You almost never call them directly; you use the syntax or built-in that triggers them.
| Syntax | Special method |
|---|---|
len(x) |
x.__len__() |
x[i] |
x.__getitem__(i) |
x + y |
x.__add__(y) |
x == y |
x.__eq__(y) |
for a in x |
x.__iter__() |
a in x |
x.__contains__(a) |
x() |
x.__call__() |
with x: |
__enter__ and __exit__ |
str(x) / repr(x) |
__str__ / __repr__ |
bool(x) |
__bool__, else __len__ |
If a special method is not suitable for the given operands, it returns NotImplemented and Python tries the other operand's reflected method (__radd__) before raising TypeError.
Usage notes
- Small integers and some short strings may be shared by the interpreter as an optimization. Never rely on
isto compare numbers or strings; the result is an implementation detail. ==falls back to identity when a class does not define__eq__.- Objects that define
__eq__without__hash__become unhashable, so they cannot be dict keys or set members. See__eq__and__hash__. - Mutable and immutable types behave very differently when shared between names; see mutable and immutable types and shallow and deep copies.
- Special methods are looked up on the type, not on the instance, so assigning
obj.__len__ = ...on one instance does not change whatlen(obj)does.
Related
- id(), type(), isinstance()
- Truth value testing
- Mutable and immutable types
- Tutorial lessons: Variables, Special methods, Memory management