PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 4, 2022

[FIXED] How to quickly figure out which list is causing the error?

 August 04, 2022     exception, list, python     No comments   

Issue

In a python script, if we have multiple lists in a single expression, for example:

a[1] = b[2] + c[3] + d[4]

OR

a[1] = b[c[d[1]]] # (This case added in EDIT)

Now, one of these lists throws an error IndexError: List Index Out of Range because the index is higher than the list length.

Is there a way to improve this default exception handling using try/except statements such that we can instantly figure out which list caused the problem?

Otherwise, one needs to check each list using a command line debugger. I understand that if an IDE is available, then this feature is probably inbuilt into the IDE.


Solution

This exact issue has been addressed and will be available in the python-3.11 interpreter . Reproduced below from the release notes: "When printing tracebacks, the interpreter will now point to the exact expression that caused the error instead of just the line. For example:"

Traceback (most recent call last):
  File "distance.py", line 11, in <module>
    print(manhattan_distance(p1, p2))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "distance.py", line 6, in manhattan_distance
    return abs(point_1.x - point_2.x) + abs(point_1.y - point_2.y)
                           ^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'x'

References:

Release notes and PEP657



Answered By - lifezbeautiful
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing