31/37
Part 6 of 6 · Follow-upsLearn and do

Key a function call so the same call always gets the same key

The second practice problem starts with a cache used the way functools.lru_cache is: it wraps a function, and the key is the call. A call arrives as a tuple args and a dict kwargs. The key has to be hashable, and the same every time for the same call. Here are three ways to build it:

import json


def flat(args, kwargs):
    return args + tuple(sorted(kwargs.items()))


def frozen(args, kwargs):
    return (args, frozenset(kwargs.items()))


def as_json(args, kwargs):
    return json.dumps([args, kwargs], sort_keys=True)


print(flat((1,), {"b": 2}), flat((1, ("b", 2)), {}))
try:
    hash(frozen(([1, 2],), {}))
except TypeError as error:
    print(error)
print(as_json((1, 2), {}), as_json((1,), {"b": 2}))
print(as_json((), {"a": 1, "b": 2}), as_json((), {"b": 2, "a": 1}))
print(as_json(((1, 2),), {}), as_json(([1, 2],), {}))
Predict

flat((1,), {"b": 2}) and flat((1, ("b", 2)), {}): one call with a keyword, one with a tuple. Same key?

Pick one to see what it prints.
Pick an answer above to see the rest