Skip to content

Commit

Permalink
Improve performance of converting URL to a string (#1170)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Oct 3, 2024
1 parent d01f70a commit 79d53eb
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
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

0 comments on commit 79d53eb

Please sign in to comment.