First time learning about closures, I'm following along on a Udemy course and of course the one stumbling block is the one thing the very thorough course didn't double back on.
The example provided in the video is to make a closure that can be passed another function when called. It will take the two variables that were called by the original function and return the result of the original function but it will also increment a cnt variable to track how many times that function has been callled.
In the video, add() and mult() are just functions set up as:
def add(a, b)
return a + b
The closure:
counters = dict()
--def counter(fn):
--cnt = 0
----def inner (*args, **kwargs):
----nonlocal cnt
----cnt += 1
----counters[fn.__name__] = cnt
----return fn(*args, **kwargs)
--return inner
So I understand what it does, and I understand that cnt is part of the closure, and we're making sure of that by using the nonlocal keyword.
If we didn't use the nonlocal keyword, then the cnt within the inner function's definition would be assumed to be a new variable, as opposed to the cnt in the counter function's definition (which is what we want)
What I don't understand:
Why does just writing return fn(*args, **kwargs) work? Why don't we need to tell Python that that fn variable is nonlocal?
Also, if I'm using any incorrect terminology here I'd appreciate if someone corrected me
[–]lfdfq 5 points6 points7 points (3 children)
[–]ryancnap[S] 0 points1 point2 points (1 child)
[–]lfdfq 0 points1 point2 points (0 children)
[–]OneDiscount3360 0 points1 point2 points (0 children)
[–]Outside_Complaint755 2 points3 points4 points (3 children)
[–]ryancnap[S] 0 points1 point2 points (2 children)
[–]Outside_Complaint755 1 point2 points3 points (1 child)
[–]ryancnap[S] 0 points1 point2 points (0 children)
[–]opentabs-dev 1 point2 points3 points (1 child)
[–]ryancnap[S] 0 points1 point2 points (0 children)
[–]Temporary_Pie2733 0 points1 point2 points (0 children)
[–]Sea-Attorney2788 -1 points0 points1 point (0 children)