Skip to content

Commit

Permalink
NEW: add make_default_hashed_key for the @cached decorators
Browse files Browse the repository at this point in the history
`make_default_key` returns a key of variable length which depends on stringified representation of the arguments. That may be undesirable, and it wouldn't hurt to hash the representation by default.
  • Loading branch information
eigenein committed Jul 28, 2022
1 parent 374e653 commit 1aa1719
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,11 @@ def expensive_function() -> int:
return 42
```

There's a few `make_key` functions provided by default:

- `cachetory.decorators.shared.make_default_key` builds a human-readable cache key out of decorated function fully-qualified name and stringified arguments. The length of the key depends on the argument values.
- `cachetory.decorators.shared.make_default_hashed_key` calls `make_default_key` under the hood but hashes the key and returns a hash hex digest – making it a fixed-length key and not human-readable.

## Supported backends

The badges indicate which schemes are supported by a particular backend, and which package extras are required for it – if any:
Expand Down
10 changes: 10 additions & 0 deletions cachetory/decorators/shared.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from hashlib import blake2s
from typing import Any, Callable


Expand All @@ -15,3 +16,12 @@ def make_default_key(callable_: Callable[..., Any], *args: Any, **kwargs: Any) -
*(f"{str(key).replace(':', '::')}={str(value).replace(':', '::')}" for key, value in sorted(kwargs.items())),
)
return ":".join(parts)


def make_default_hashed_key(callable_: Callable[..., Any], *args: Any, **kwargs: Any) -> str:
"""
Generates a hashed cache key given the callable and the arguments it's being called with.
Uses ``blake2s`` as the fastest algorithm from ``hashlib``.
"""
return blake2s(make_default_key(callable_, *args, **kwargs).encode()).hexdigest()
13 changes: 12 additions & 1 deletion tests/decorators/test_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from pytest import mark

from cachetory.decorators.shared import make_default_key
from cachetory.decorators.shared import make_default_hashed_key, make_default_key


def _callable():
Expand Down Expand Up @@ -39,3 +39,14 @@ def test_make_default_key(
expected_key: str,
):
assert make_default_key(callable_, *args, **kwargs) == expected_key


def test_make_default_hashed_key():
"""
``make_default_hashed_key`` calls ``make_default_key`` under the hood,
thus one smoke test is enough.
"""
assert (
make_default_hashed_key(_callable, "a:b", foo="bar")
== "dc3305eaf5bc29bc29d70c3dbf7676c49bfd552cfbec17106fdf71cc01d176c9"
)

0 comments on commit 1aa1719

Please sign in to comment.