Skip to content

Commit

Permalink
Optimize building query strings with MultiDict (#1256)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Oct 13, 2024
1 parent 642b5e2 commit 5d6ff6c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGES/1256.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved performance of constructing query strings from :class:`~multidict.MultiDict` -- by :user:`bdraco`.
16 changes: 12 additions & 4 deletions yarl/_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -1263,16 +1263,20 @@ def _get_str_query_from_sequence_iterable(
"""
quoter = self._QUERY_PART_QUOTER
pairs = [
f"{quoter(k)}={quoter(self._query_var(v))}"
f"{quoter(k)}={quoter(v if type(v) is str else self._query_var(v))}"
for k, val in items
for v in (val if isinstance(val, (list, tuple)) else (val,))
for v in (
val
if type(val) is not str and isinstance(val, (list, tuple))
else (val,)
)
]
return "&".join(pairs)

@staticmethod
def _query_var(v: QueryVariable) -> str:
cls = type(v)
if cls is str or issubclass(cls, str):
if issubclass(cls, str):
if TYPE_CHECKING:
assert isinstance(v, str)
return v
Expand Down Expand Up @@ -1305,7 +1309,11 @@ def _get_str_query_from_iterable(
quoter = self._QUERY_PART_QUOTER
# A listcomp is used since listcomps are inlined on CPython 3.12+ and
# they are a bit faster than a generator expression.
return "&".join([f"{quoter(k)}={quoter(self._query_var(v))}" for k, v in items])
pairs = [
f"{quoter(k)}={quoter(v if type(v) is str else self._query_var(v))}"
for k, v in items
]
return "&".join(pairs)

def _get_str_query(self, *args: Any, **kwargs: Any) -> Union[str, None]:
query: Union[str, Mapping[str, QueryVariable], None]
Expand Down

0 comments on commit 5d6ff6c

Please sign in to comment.