From 78c16165858ae38dd586f5ceb2e4d78d4846fa3e Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 17 Oct 2024 15:28:12 -1000 Subject: [PATCH] Improve performance of `URL.with_scheme` (#1322) --- CHANGES/1322.misc.rst | 1 + yarl/_url.py | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) create mode 100644 CHANGES/1322.misc.rst diff --git a/CHANGES/1322.misc.rst b/CHANGES/1322.misc.rst new file mode 100644 index 000000000..23b7d6263 --- /dev/null +++ b/CHANGES/1322.misc.rst @@ -0,0 +1 @@ +Improved performance of the :py:meth:`~yarl.URL.with_scheme` method -- by :user:`bdraco`. diff --git a/yarl/_url.py b/yarl/_url.py index 630be469b..f978d0616 100644 --- a/yarl/_url.py +++ b/yarl/_url.py @@ -1172,13 +1172,15 @@ def with_scheme(self, scheme: str) -> "URL": if not isinstance(scheme, str): raise TypeError("Invalid scheme type") lower_scheme = scheme.lower() - if not self._val.netloc and lower_scheme in SCHEME_REQUIRES_HOST: + _, netloc, path, query, fragment = self._val + if not netloc and lower_scheme in SCHEME_REQUIRES_HOST: msg = ( "scheme replacement is not allowed for " f"relative URLs for the {lower_scheme} scheme" ) raise ValueError(msg) - return self._from_val(self._val._replace(scheme=lower_scheme)) + val = tuple.__new__(SplitResult, (lower_scheme, netloc, path, query, fragment)) + return self._from_val(val) def with_user(self, user: Union[str, None]) -> "URL": """Return a new URL with user replaced.