Functions in Depth
Scope rules, closures and iterators — how functions really work.
Easy
Functions are objects: they can be stored, passed and returned. Understanding scope and closures explains decorators and many library APIs.
Sub-topics (3)
Scope and the LEGB Rule
Names are looked up in Local, Enclosing, Global, then Built-in scope.
Easy♥ 0🔖 0💬 0
Closures
A nested function that remembers variables from the function that created it.
Intermediate♥ 0🔖 0💬 0
Iterators and the Iterator Protocol
Any object with __iter__ and __next__ can be looped over; next() raises StopIteration at the end.
Intermediate♥ 0🔖 0💬 0
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.