Python in Depth
Python past the everyday: how names bind to objects, what a decorator, a generator and a method really are, and what the interpreter does with your file. Every surprise is a snippet you predict first and then watch run.
- Intermediate
- 4 units, 12 lessons, 154 exercises
- Python
- Builds on everyday Python, or Python: Zero to Hero
Unit 01 · 3 lessons
Names and objects
Predict what any assignment, comparison or loop does to the objects behind the names
- 01Names and objects
Labels, not boxes: aliasing, defaults and copies
- 02The data model
Operators are methods: equality, hashing, repr and friends
- BOSSHow for works
Iterators, generators and a pipeline that never builds a list
Read the unit guide
A Python variable is a label stuck on an object, not a box holding a value. Assignment never copies: b = a gives one object two names. == asks whether two objects have equal values, is asks whether they are the same object. Mutate an object through one name and every other name sees it; rebind a name and nothing else moves.
That one idea explains the classic traps. [[0] * 2] * 3 is one row with three labels. A default argument is created once, when def runs, so a mutable default is shared by every call (use None and create the list inside). += mutates a list in place but builds a new string. A shallow copy is a new outer list with the same inner objects; only copy.deepcopy copies every level.
Operators and built-ins are method calls in disguise. a == b calls __eq__, len(x) calls __len__, x[i] calls __getitem__, a + b calls __add__, and print uses __str__ while containers and the prompt use __repr__. Define those methods and your class behaves like a built-in.
Equality and hashing travel together. Objects that compare equal must have equal hashes, so a class that defines __eq__ loses its default __hash__ until you write one from the same fields. Never change a field the hash depends on while the object sits in a set or a dict: it is filed under the old hash and becomes unfindable. @dataclass writes __init__, __repr__ and __eq__ for you.
A for loop is two built-ins: iter(obj) asks for an iterator, then next() is called until StopIteration. An iterable can hand out fresh iterators; an iterator is a one-way cursor that is empty once used. A generator function pauses at each yield and resumes on the next next(), which makes pipelines lazy: nothing is read until someone asks.
The pitfall of the unit: treating a second name as a copy, and treating a generator as a list. Both look fine until the second use.
Unit 02 · 3 lessons
Functions
Read closures, decorators and context managers as the plain function calls they are
- 01Scope and closures
Where a name is looked up, and functions that remember
- 02Decorators
Functions that take a function and return a replacement
- BOSSWith and exceptions
Cleanup that always runs, from try/finally to your own with block
Read the unit guide
A name is looked up in four places, in order: the local scope of the function, any enclosing functions, the module's globals, then the built-ins. The lookup happens when the line runs, not when the function is defined. Assignment is different: a name assigned anywhere in a function is local to it for the whole body, unless you declare it global or nonlocal. That is why reading a global works and count += 1 on it raises UnboundLocalError.
A closure is an inner function that keeps using variables of the function that made it, after that function has returned. It keeps the variable, not a snapshot of its value. Three lambdas made in a loop all see the loop variable's final value; bind the value at creation time with a default argument (lambda i=i: ...) or a factory function.
A decorator is a function that takes a function and returns a replacement. @deco above def f means exactly f = deco(f), and it runs once, at definition time. The replacement is usually a wrapper that accepts *args, **kwargs, does something extra and calls the original; functools.wraps copies the original's name and docstring onto it. Stacked decorators apply bottom up. A decorator with arguments is a function that returns a decorator: three levels.
functools.lru_cache is the decorator you will use most: it stores results in a dict keyed by the arguments, so arguments must be hashable, and callers share the cached object.
try has four clauses: except runs if a matching exception was raised, else if none was, finally always and last, even on return. The first matching except wins, so list specific exceptions before general ones. A bare raise re-raises; raise New(...) from err chains.
with is try/finally packaged: __enter__ runs before the block and __exit__ after it, error or not. contextlib.contextmanager builds one from a generator: code before yield is the setup, code after is the cleanup, and the cleanup must sit in finally or an exception in the block skips it.
Unit 03 · 3 lessons
Classes
Explain any attribute access: where Python looks, in what order, and what it does with what it finds
- 01Attributes
Instance or class, properties, and what super() really calls
- 02Types and protocols
Hints the interpreter ignores and a checker reads
- BOSSHow methods work
Where self comes from, and the protocol behind property
Read the unit guide
Reading obj.name searches the instance's own dict, then the class, then each base class in the method resolution order (MRO). Writing obj.name = value always writes to the instance. Those two rules explain the classic surprise: a list defined in the class body is one object shared by every instance, while self.count += 1 reads the class value and then stores a private copy on the instance. Per-instance state belongs in __init__.
The MRO is a single line of classes: a class comes before its parents, and parents keep the order of the class statement. super() means "the next class in the MRO of this object", which with multiple inheritance may be a sibling rather than a parent. cls.__mro__ shows the line.
A property is a method that is read like an attribute, with an optional setter that can validate. It lets a class start with plain attributes and add logic later without changing its callers.
Type hints are metadata. The interpreter stores them and ignores them; a type checker such as mypy or pyright reads them without running the program. int | None makes the checker insist on a None check, list[int] and type variables describe containers and generic functions, and a Protocol is duck typing written down: any class with the right methods matches, no inheritance needed. An abstract base class is the run-time cousin: it refuses to instantiate a subclass that has not implemented every abstract method.
Methods are not magic either. A function stored on a class has a __get__ method; looking it up through an instance calls it, and the result is a bound method that remembers the instance. Objects with __get__ are descriptors, and property, classmethod and staticmethod are all built that way. A descriptor that also defines __set__ beats the instance dict; one with only __get__, like a function, loses to it.
Two more hooks: __getattr__ runs only when normal lookup fails, and __slots__ replaces the per-instance dict with fixed fields, so no new attributes can be added.
Unit 04 · 3 lessons
The runtime
Know what the interpreter does with your files, your threads and your loops
- 01Imports
What import runs, what it caches, and how cycles break
- 02The GIL
Threads for waiting, processes for computing, asyncio between
- BOSSFast Python
Count the operations, then hand the loop to C
Read the unit guide
The first import shop in a program finds shop.py, creates a module object, stores it in sys.modules and then runs the file top to bottom inside it. Every later import of that name, from any file, finds the stored module and only binds a name. So a module's top-level code runs once, and its globals are shared by everyone who imports it. from shop import total copies the current binding into your namespace: if the module rebinds total later, your copy does not follow.
Every module has a __name__. It is the module's name when imported and the string "__main__" in the file you ran, which is all if __name__ == "__main__": tests. A package is a folder of modules; importing shop.cart first runs shop/__init__.py.
Because a module is stored before its code runs, two modules can import each other without looping forever. The second one simply sees the first half-built. from a import x then fails if x is not defined yet; import a with a.x used later inside a function works. The durable fix is to remove the cycle: move what both need into a third module.
The default CPython build has a global interpreter lock (GIL): only one thread executes Python bytecode at a time. Threads still help when the work is waiting (network, disk, sleep), because a waiting thread lets the GIL go. For pure-Python computation they do not, and the tool is processes: each has its own interpreter, its own GIL and its own memory. asyncio is a third shape: one thread, many tasks, switching only at await. A build of CPython without the GIL exists, but it is a separate build you have to choose.
The GIL does not make your code thread-safe. count += 1 is a read and then a write, and another thread can run in between, so shared updates still need a lock.
Fast Python is mostly counting. A dict or set jumps to a key by its hash; a list checks item after item. A lookup inside a loop multiplies the two sizes. Fix the count first, then move the remaining loop into C with a built-in such as sum, any or sorted, or with NumPy when the data is a large array of numbers. Profiling, in the performance roadmap, tells you which loop is worth it.
Learn Python in Depth on your phone.
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.