diff --git a/CHANGES/1170.misc.rst b/CHANGES/1170.misc.rst new file mode 100644 index 00000000..9f27309d --- /dev/null +++ b/CHANGES/1170.misc.rst @@ -0,0 +1 @@ +Improved performance of converting :class:`~yarl.URL` to a string when no explicit port is set -- by :user:`bdraco`. diff --git a/tests/test_url.py b/tests/test_url.py index 49245b8d..9947b950 100644 --- a/tests/test_url.py +++ b/tests/test_url.py @@ -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(): diff --git a/yarl/_url.py b/yarl/_url.py index 3f3a6d9f..bac600d7 100644 --- a/yarl/_url.py +++ b/yarl/_url.py @@ -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: