Skip to content

Commit

Permalink
Improve performance of handling ports in the URL (#1081)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Sep 2, 2024
1 parent 33ac3f1 commit f978d5e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
1 change: 1 addition & 0 deletions CHANGES/1081.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved performance of handling ports -- by :user:`bdraco`.
24 changes: 14 additions & 10 deletions yarl/_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ def __str__(self):
val = self._val
if not val.path and self.is_absolute() and (val.query or val.fragment):
val = val._replace(path="/")
if (port := self._get_port()) is None:
if (port := self._port_not_default) is None:
# port normalization - using None for default ports to remove from rendering
# https://datatracker.ietf.org/doc/html/rfc3986.html#section-6.2.3
val = val._replace(
Expand Down Expand Up @@ -371,7 +371,7 @@ def is_default_port(self):
if self.explicit_port is None:
# A relative URL does not have an implicit port / default port
return self.port is not None
default = self._get_default_port()
default = self._default_port
if default is None:
return False
return self.port == default
Expand Down Expand Up @@ -421,17 +421,21 @@ def raw_authority(self):
"""
return self._val.netloc

def _get_default_port(self) -> Union[int, None]:
@cached_property
def _default_port(self) -> Union[int, None]:
"""Default port for the scheme or None if not known."""
scheme = self.scheme
if not scheme:
return None
return DEFAULT_PORTS.get(scheme)

def _get_port(self) -> Union[int, None]:
"""Port or None if default port"""
if self._get_default_port() == self.port:
@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:
return None
return self.port
return port

@cached_property
def authority(self):
Expand Down Expand Up @@ -520,9 +524,9 @@ def port(self):
scheme without default port substitution.
"""
return self._val.port or self._get_default_port()
return self.explicit_port or self._default_port

@property
@cached_property
def explicit_port(self):
"""Port part of URL, without scheme-based fallback.
Expand Down Expand Up @@ -1142,7 +1146,7 @@ def human_repr(self):
user,
password,
host,
self._val.port,
self.explicit_port,
encode_host=False,
),
path,
Expand Down

0 comments on commit f978d5e

Please sign in to comment.