3 ms·
Closures are the context in which a function executes. The best way to demonstrate this is with a silly example that sticks in the mind: def learn_how_to_gre
by algorias 17y ago
Closures are the context in which a function executes. The best way to demonstrate this is with a silly example that sticks in the mind:
def learn_how_to_greet(formal=True):
if formal:
string = "Good day, Mr. {last_name}."
else:
string = "What's up, {first_name}?"
def greet(**kwds):
return string.format(**kwds)
return greet
- csbrooks 17y agoWhat happens if you do: def learn_how_to_greet(formal=True): if formal: string = "Good day, Mr. {last_name}." else: string = "What's up, {first_name}?" def greet(**kwds): return string.format(**kwds) ret = greet string = "WHOA! Look at me!" return ret In other words, at what point do the variables used in the "greet" function get saved off? And what is saved, the variable name itself, or the data in it?
- pufuwozu 17y ago>>> learn_how_to_greet()(first_name="Joe", last_name="Smith") 'WHOA! Look at me!'
- dazmax 17y agoIt should be saved as its value at the point of greet's definition, but Python appears to not have real closures, so the change in the value of string afterwards changes it in greet too.
- oconnor0 17y agoWhy do you say that the value should be saved at its definition? I realize Java does that (with anonymous classes & final), but allowing mutation of closured state lets you fairly easily write things - like an OO class system, if you want to.
- algorias 17y agoWhat does "real" mean? When you use closures (or not-quite-closures, or however you want to call them) in python, they work just like "real" closures, except for the pathological case of defining functions in loops.
- algorias 17y agoI think it happens when the closing scope stops being local (i.e. at the time the defined function gets returned).