About the scope: Python knows in principal only 2 scopes: local and global. If you define a function (or a class) Python creates a new emtpy/filled with the function arguments local scope (system table). That gets filled successively by local variable assignments etc. There happens a little bit of magic: if you use a variable of the next higher scope, it gets copied (!) to the local scope. You can follow that easily by print(locals()). (You can also use the global scope, but that is another topic).
Edit: had to clarify some points
Isn't that exactly what GP said? And gave an example how to create that effect explicitly in functional languages, using refs?
Pass a keyword argument with the default value equal to the value you want to close over.
Voila!
The closure returns whatever object the name refers at the moment. That is all.
def loop():
for i in range(10):
yield lambda j=i: j
`j` refers to the same object (int) `i` refers to at the time of the lambda creation (the desired result). `j` is local to the lambda (each lambda has its own local namespace).Just `lambda: i` code would result in an object that `i` refers to at the time of calling the lambda (`i` name is not local to the lambda).
https://docs.python.org/3/faq/programming.html#why-do-lambda...
In safe languages like ML you would have to create an explicit reference to get that effect, and then it is obvious to the reader.
Python is not built for complex abstractions, but unfortunately it is (ab)used for that, particularly in machine learning.