+ 10
Question about closures in python
We don't inner functions have access to s,f https://code.sololearn.com/cMq02ZJWjaLl/?ref=app
17 Réponses
+ 8
Frogged
Instead of changing the values of the variables 's' and 'f', new variables local to b() and c() named 's' & 'f' are being created.
I'm not sure about this part, but I think that Python thinks in the right-hand-side of
`f, s = s, f`
we are referencing the local variables 's' and 'f'.
This is because changing 'f' and 's' to any other name works
`a, b = f, s`
I don't think there is any way to mutate the 'f' and 's' variables of the a() function without making them global. But maybe someone else can suggest a way?
My suggestion is to make a list instead of the variables, like so
lst = [True, False]
And then replace every 's' with lst[0] and 'f' with lst[1]
+ 8
Frogged yep , similar to how you can set attributes of classes and objects, you can also set attributes to functions.
Useful when you want the option to retrieve some variable, but not explicity return it with the return statement. Also attributes can be set from inside the function definition or from outside the function definition.
+ 4
XXX yes..
I think, Python is not clean here....
Finally :
in a python closure all variables that are shared and changed by inner functions should be put into a mutable container.
or..Vitaly Sokol thanks..
alternatively each one is to be marked as non-local
+ 2
It is to understand closures
+ 1
? its still a function. works the same no matter the scope.
you added a function inside of another functions scope, the variables still need to be passed just like if you created to variables and made a function.
you need to pass them or make them global
+ 1
that goes with every variable
+ 1
why wouldn't you just use a chain of elifs?
+ 1
also you can do it with function attributes:
https://code.sololearn.com/chMKa1VykhF0/?ref=app
+ 1
Vitaly Sokol that's great
+ 1
Calvin Thomas they are declared in the outer function. not globally.
that's a point in closures:
Although the outer function is no more in the memory, its variables are accessible and can be shared by the functions created and returned from outer function.
0
because of namespaces.
you cant reference a variable inside a function without either passing the variable to the function or making the variable global
0
@slick but it is a closure
no prob for accessing i
0
How about i
0
But I have access
0
Why doesn't "global f, s" work here? Am I not making f and s global variables?
0
Frogged I see, thanks for the explanation.