Skip to content

Comments

Fix IndexError in URL.replace() when netloc is empty#3154

Closed
bysiber wants to merge 1 commit intoKludex:mainfrom
bysiber:fix-url-replace-empty-netloc
Closed

Fix IndexError in URL.replace() when netloc is empty#3154
bysiber wants to merge 1 commit intoKludex:mainfrom
bysiber:fix-url-replace-empty-netloc

Conversation

@bysiber
Copy link

@bysiber bysiber commented Feb 20, 2026

Summary

URL.replace() raises an IndexError when called with username, password, or port arguments on a URL that has no network location (e.g. a relative path or empty URL).

Reproduction

from starlette.datastructures import URL

url = URL("/some/path")
url.replace(username="user")  # IndexError: string index out of range

Cause

When hostname is not provided in the kwargs, the code tries to extract it from the current netloc. If the netloc is empty (as it is for path-only URLs), rpartition("@") returns an empty string for hostname, and the subsequent hostname[-1] indexing raises IndexError.

Fix

Added a truthiness check (if hostname and hostname[-1] != "]") to guard against indexing into an empty string.

When calling replace() with username, password, or port on a URL that
has no network location (empty netloc), the code extracts hostname
from the netloc via rpartition('@'). If the netloc is empty, hostname
becomes an empty string, and the subsequent hostname[-1] indexing
raises an IndexError.

Adding a truthiness check before indexing prevents the crash and
allows the empty hostname to pass through to the URL reconstruction.
@Kludex
Copy link
Owner

Kludex commented Feb 20, 2026

Test

@Kludex Kludex closed this Feb 22, 2026
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.

2 participants