Skip to content
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/75.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Cache ``to_camel_case``, speeding up building and serialising DIDL objects
5 changes: 5 additions & 0 deletions didl_lite/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Utilities."""

import functools
import re

NAMESPACES = {
Expand Down Expand Up @@ -42,6 +43,10 @@ def split_namespace_tag(namespaced_tag: str) -> tuple[str | None, str]:
return namespace, tag


# Cached: called for every attribute set on a DidlObject, with a small closed
# set of property names. Bounded, as from_xml also passes names read from
# documents received from other devices.
@functools.lru_cache(maxsize=256)
def to_camel_case(name: str) -> str:
"""Get camel case of name."""
sub1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
Expand Down
12 changes: 11 additions & 1 deletion tests/test_didl_lite.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import pytest
from defusedxml import ElementTree as ET

from didl_lite import didl_lite
from didl_lite import didl_lite, utils

NAMESPACES = {
"didl_lite": "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/",
Expand Down Expand Up @@ -793,3 +793,13 @@ def test_music_track_artist_and_genre(self) -> None:

assert b"<upnp:artist>My Artist</upnp:artist>" in xml
assert b"<upnp:genre>My Genre</upnp:genre>" in xml

def test_to_camel_case_is_cached(self) -> None:
"""Test to_camel_case is cached, and used cached through didl_lite."""
assert hasattr(utils.to_camel_case, "cache_info")
# didl_lite imports the name; it must be the cached function too.
assert didl_lite.to_camel_case is utils.to_camel_case

hits_before = utils.to_camel_case.cache_info().hits
didl_lite.MusicTrack(id="0", parent_id="0", title="Title", restricted="1")
assert utils.to_camel_case.cache_info().hits > hits_before
Loading