Title: For Loop temporary variable scope should be local to For loop
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.9
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: deb_ctc, steven.daprano
Priority: normal Keywords:

Created on 2021-06-07 04:56 by deb_ctc, last changed 2021-06-07 06:58 by mark.dickinson. This issue is now closed.

Messages (3)
msg395246 - (view) Author: Debasis Satapathy (deb_ctc) Date: 2021-06-07 04:56
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
for x in numbers:

In the above code, print(x) statement should give error. Because x scope should be local to for loop only.
99% cases, developers will not use the temporary variable x outside of the for loop.
So x will keep on consuming memory always. So it is a bad usage of memory.
Ideally x memory should be free once for loop execution is completed.
msg395247 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2021-06-07 05:43
This is not a bug, it is intentional design and has been since Python 1.

You are incorrect about x consuming memory "always". If the value bound to x is in use elsewhere, deleting x will save no memory. If the value is not in use elsewhere, it will be garbage collected as soon as x goes out of scope, which will be at the end of the function.

Shifting to block-scope for for-loops has been discussed before, it is not a popular idea and I expect that most people will oppose it. You can search the Python-Ideas mailing list if you want to find out more. If you still feel strongly that this is an enhancement, as it is a major change in language behaviour it would require a PEP to be written.

Even if the PEP was accepted, the earliest it could go into the language would be Python 3.11 or better, and that would likely require a special `__future__` import.
msg395248 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2021-06-07 05:45
By the way, loop variables are not considered to be "temporary" in Python. They are no more temporary than any other local variable -- they *are* local variables with exactly the same scope and lifetime as all other local variables.
Date User Action Args
2021-06-07 06:58:19mark.dickinsonsetstatus: open -> closed
2021-06-07 05:45:45steven.dapranosetmessages: + msg395248
2021-06-07 05:43:32steven.dapranosetnosy: + steven.daprano
messages: + msg395247

resolution: not a bug
stage: resolved
2021-06-07 04:56:39deb_ctccreate