Skip to content

Comments

Fix WeakSequence.__getitem__ catching KeyError instead of IndexError#13136

Open
bysiber wants to merge 2 commits intosqlalchemy:mainfrom
bysiber:fix/weak-sequence-keyerror
Open

Fix WeakSequence.__getitem__ catching KeyError instead of IndexError#13136
bysiber wants to merge 2 commits intosqlalchemy:mainfrom
bysiber:fix/weak-sequence-keyerror

Conversation

@bysiber
Copy link

@bysiber bysiber commented Feb 20, 2026

Description

WeakSequence.__getitem__ catches KeyError but the internal _storage is a list, which raises IndexError for out-of-range access. This means the except KeyError handler never executes, and the custom error message is never shown.

Current behavior

def __getitem__(self, index):
    try:
        obj = self._storage[index]  # _storage is a list
    except KeyError:  # lists don't raise KeyError
        raise IndexError("Index %s out of range" % index)
    else:
        return obj()

On an out-of-range index, the raw IndexError from list access propagates directly (e.g., list index out of range) instead of the intended custom message.

Fix

Changed except KeyError to except IndexError so the handler actually catches the exception raised by list indexing.

WeakSequence._storage is a list, which raises IndexError on
out-of-range access. The except block was catching KeyError,
making it dead code — the original IndexError always propagated
unhandled.
@CaselIT
Copy link
Member

CaselIT commented Feb 20, 2026

hi,

I would just remove the try / except here, since there is no need to re-raise the same type of exception

@bysiber
Copy link
Author

bysiber commented Feb 20, 2026

Good call, simplified it — removed the try/except entirely since _storage is a list and already raises IndexError on its own.

@CaselIT CaselIT requested a review from sqla-tester February 21, 2026 11:35
Copy link
Collaborator

@sqla-tester sqla-tester left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, this is sqla-tester setting up my work on behalf of CaselIT to try to get revision ceb8f9f of this pull request into gerrit so we can run tests and reviews and stuff

@sqla-tester
Copy link
Collaborator

New Gerrit review created for change ceb8f9f: https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/6603

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants