Fix IndexError in URL.replace() on a URL with no authority#3317
Merged
Conversation
URL.replace() raised IndexError when changing an authority component (port, username, or password) on a URL with an empty netloc, such as a path-only URL. The hostname derived from the empty netloc was an empty string, and indexing it with hostname[-1] failed. Guard the bracket check so the rsplit is skipped when hostname is empty. A path-only URL now gains the requested component in its netloc instead of crashing.
There was a problem hiding this comment.
No issues found across 2 files
Tip: cubic could auto-approve low-risk PRs like this, if it thinks it's safe to merge. Learn more
Re-trigger cubic
3 tasks
Kludex
approved these changes
Jun 10, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
URL.replace() raises IndexError when you change an authority component on a URL that has no authority. This happens for path-only URLs, where the netloc is empty.
A small reproduction:
The cause is in the branch that derives the existing hostname when the caller does not pass one. The netloc is empty, so after rpartition("@") the hostname is also empty, and the bracket check then indexes an empty string:
This guards that check so the split is only attempted when there is a hostname to split. A path-only URL now gains the requested component in its netloc instead of crashing, which matches what already happens when you pass hostname explicitly:
I added assertions to the existing test_url test covering the port and username cases on a URL with no authority. The new cases fail with IndexError before the change and pass after it. ruff check and ruff format --check both pass on the touched files.