Transcrypt icon indicating copy to clipboard operation
Transcrypt copied to clipboard

list.index does not raise exception

Open faerot opened this issue 5 years ago • 2 comments

In python when item not found it raises IndexError exception. Here it just returns javascript Array.indexOf call.

Expected solution: check if result is -1 and raise exception for consistency.

faerot avatar May 30 '19 07:05 faerot

it raises ValueError exception (not IndexError) in Python3.9.

chopin avatar May 02 '24 03:05 chopin

By default, in an effort to maintain runtime performance, indexed lookups in Transcrypt default to using native JS lookups that only return undefined for an invalid index. This is the reason that enabling operator overloading for processing negative indices is required, as it will instead call a custom __getitem__ method for handling indexed lookups. As a compromise, I've added index validation to that same __getitem__ method that is used when operator overloading is enabled with the opov pragma. In that case, the following would result in an exception that can be caught:

lst = ['a', 'b', 'c']
try:
    idx_val = lst[4]  # __:opov
    print(idx_val)
except Exception as e:
    print(f"{type(e).__name__}: {e}")

# IndexError: index out of range

Autotests are all passing with this change, though I am concerned with potential backwards compatibility issues that some may have. That said, enabling this behavior with opov moves it closer to that of CPython even if it is a bit less performant.

This feature will be added in v3.9.4

JennaSys avatar Jul 29 '24 02:07 JennaSys