This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Feature request: Throw an error when making impossible evaluation against an empty list
Type: enhancement Stage: resolved
Components: Parser Versions: Python 3.11
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: JelleZijlstra, Luminair, eric.smith, lys.nikolaou, pablogsal
Priority: normal Keywords:

Created on 2022-04-02 15:22 by Luminair, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (4)
msg416559 - (view) Author: Luminair (Luminair) Date: 2022-04-02 15:22
Below are four examples of impossible code that operates on nothing. The latter two continue silently, throwing no errors. I saw a bug sneak by because of this. I wonder if it is within the scope of Python's design to throw Exceptions in these situations? 

x = 

for x in : print("This code is never reached")

while(None): print("This code is never reached")

emptylist = []
for x in emptylist:
    if emptylist[x] == "This code is never reached":
        print("This code is never reached")
    else: print("This code is never reached")
msg416560 - (view) Author: Jelle Zijlstra (JelleZijlstra) * (Python committer) Date: 2022-04-02 15:35
This sort of thing would be better caught by a linter or type checker. For example, mypy with the `--warn-unreachable` option will flag the `while None:` example.

Iterating over an empty list will not currently be caught by mypy, but it's common in real code to iterate over a list that may be empty, so it would be a major compatibility break for Python to error when iterating over an empty list.
msg416561 - (view) Author: Luminair (Luminair) Date: 2022-04-02 15:39
Thank you for the quick response Jelle! I do like mypy, and I will file this with them. Good luck with the migration to GitHub :)
msg416564 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2022-04-02 16:40
As Jelle says, this can't be a runtime Exception.

At best mypy or a linter could make iterating over an known empty list (like a literal []) a warning, not an error as suggested by the OP. I sometimes "comment out" loops by doing something like:

for i in []: # long_list_returning_function():
    # lots of code here

I do this just to avoid re-indenting everything if I want to skip the loop during development.
History
Date User Action Args
2022-04-11 14:59:58adminsetgithub: 91358
2022-04-02 16:40:10eric.smithsetnosy: + eric.smith
messages: + msg416564
2022-04-02 15:39:10Luminairsetmessages: + msg416561
2022-04-02 15:35:22JelleZijlstrasetstatus: open -> closed

nosy: + JelleZijlstra
messages: + msg416560

resolution: rejected
stage: resolved
2022-04-02 15:22:18Luminaircreate