Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve performance of converting URL to a string #1170

Merged
merged 2 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/1170.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved performance of converting :class:`~yarl.URL` to a string when no explicit port is set -- by :user:`bdraco`.
8 changes: 8 additions & 0 deletions tests/test_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,35 +304,43 @@ def test_port_for_implicit_port():
def test_port_for_relative_url():
url = URL("/path/to")
assert url.port is None
assert url._port_not_default is None
assert url.explicit_port is None


def test_port_for_unknown_scheme():
url = URL("unknown://example.com")
assert url.port is None
assert url._port_not_default is None
assert url.explicit_port is None


def test_explicit_port_for_explicit_port():
url = URL("http://example.com:8888")
assert 8888 == url.explicit_port
assert url.explicit_port == url._val.port
assert url._port_not_default == 8888


def test_explicit_port_for_implicit_port():
url = URL("http://example.com")
assert url.explicit_port is None
assert url.explicit_port == url._val.port
assert url._port_not_default is None


def test_explicit_port_for_relative_url():
url = URL("/path/to")
assert url.explicit_port is None
assert url.explicit_port == url._val.port
assert url._port_not_default is None


def test_explicit_port_for_unknown_scheme():
url = URL("unknown://example.com")
assert url.explicit_port is None
assert url.explicit_port == url._val.port
assert url._port_not_default is None


def test_raw_path_string_empty():
Expand Down
6 changes: 3 additions & 3 deletions yarl/_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,10 +603,10 @@ def _default_port(self) -> Union[int, None]:
@cached_property
def _port_not_default(self) -> Union[int, None]:
"""The port part of URL normalized to None if its the default port."""
port = self.port
if self._default_port == port:
explicit_port = self.explicit_port
if explicit_port is None or explicit_port == self._default_port:
return None
return port
return explicit_port

@cached_property
def authority(self) -> str:
Expand Down
Loading