The variables (names) 'f' and 'g' are reused every time the loop iterates.
You are correct that doing an explicit 'del' within the loop would presumably prevent the magic mutation-not-binding behavior under discussion. I still don't want the behavior, but I admit that's a pretty easy way to be more explicit if it were added.
On Thu, Jun 27, 2019 at 09:55:53AM -0400, David Mertz wrote:
> On Thu, Jun 27, 2019 at 9:13 AM Steven D'Aprano <firstname.lastname@example.org> wrote:
> > The only risk here is if your refactoring does something silly, such as
> > reusing a variable which overrides assignment:
> How would you propose to write this code without reusing a variable?
> def frobnicate(data):
> stuff = 
> for datum in data:
> f = process_the(data)
> g = munge_result(f)
> return stuff
Rewrite it in what way? What problem are you trying to solve?
If you just want to "flush" the local variables at the end of each loop
and ensure that they have been deleted, you can explicitly delete them:
del f, g, datum
If you are talking about the kind of refactoring Chris was talking
about, I don't see any reason, or opportunity, to do that. If anything,
you could reverse the refactoring:
stuff = 
for datum in data:
which leads to the obvious comprehension:
return [munge_result(process_the(datum)) for datum in data]
which allows us to eliminate the variable re-use:
return list(map(lambda x: munge_result(process_the(x)), data))
> looking at the source code in `process_the()` we have no way of knowing
> whether `f` is being bound to a new object each time or some completely
> different arbitrary action.
That's exactly the situation right now. Functions can perform arbitrary
actions and return the same object each time.
print("do something arbitrary")
Python-ideas mailing list -- email@example.com
To unsubscribe send an email to firstname.lastname@example.org
Message archived at https://email@example.com/message/OCJYGIXC3MBQGMJ532GEHWUXII5AAFWX/
Code of Conduct: http://python.org/psf/codeofconduct/