+ 1

What are the advantages of closures over pseudo-closures?

I want to follow up on a question I asked yesterday. One of the answers I got gave this link, and the first answer there brings up what I'm going to ask about. https://stackoverflow.com/questions/4020419/why-arent-JUMP_LINK__&&__python__&&__JUMP_LINK-nested-functions-called-closures The poster explains what a closure is by comparing two versions of a function. 1.) def make_printer(msg): def printer(): print(msg) return printer 2.) def make_printer(msg): def printer(msg=msg): print(msg) return printer The first function is a true closure, because the inner function, called from outside later, will try to access a value that will be gone by then - or would be, if it wasn't for printer.__closure__. The second version passes the value as a default-argument so that the function won't have to go for nonlocals. Function-wise they be the same. But if that's the case, what is the advantage of a genuine closure?

27th Jan 2019, 7:34 PM
HonFu
HonFu - avatar
2 Respostas
+ 5
Let's do a test Change the global variable after calling, and see what happens. https://code.sololearn.com/cEG88XkY6Rvp/?ref=app Test 1 result: seems same in this case. Let me try editing the variable in the inner function https://code.sololearn.com/chdG5r1uPf1y/?ref=app Test 2 result: Still seems the same 🤷‍♂️
31st Jan 2019, 9:42 AM
Gordon
Gordon - avatar
+ 2
Aaaaaaah! 😅
31st Jan 2019, 9:55 AM
HonFu
HonFu - avatar