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:
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.
Three things trip people up: positional against keyword arguments, unhashable arguments and keyword order. Each line of the output matches one item below, with the fix and its price:
Positional against keyword. Flattened into one tuple, f(1, b=2) and f(1, ("b", 2)) both became (1, ('b', 2)): two different calls with one key. So keep args and kwargs as two separate parts. f(1, 2) and f(1, b=2) then get two keys: a duplicate entry, never a wrong answer.
Unhashable arguments.frozen keeps the parts apart and ignores keyword order. But hashing it for f([1, 2]) raised TypeError: unhashable type: 'list'.
One JSON string keeps the parts apart.json.dumps([args, kwargs], sort_keys=True) gives f(1, 2) and f(1, b=2) two keys, and a list in the arguments is no problem.
Keyword order.f(a=1, b=2) and f(b=2, a=1) are one call, and sort_keys=True gives them one key: it sorts the keys of every dict at every depth. lru_cache doesn't promise that: its docs say the two calls may get separate entries.
The price. JSON has no tuples, so f((1, 2)) and f([1, 2]) share a key.
So when the arguments are JSON-style data, one string handles all three traps.
In the editor, write make_key(args, kwargs) the third way, and pay back its price: f((1, 2)) and f([1, 2]) must get different keys, at any depth. It prints two keys that differ, then True for two keyword orders.
Pick an answer above to see the rest
Instructions
1
Write make_key(args, kwargs): one JSON string per call, as above, except that f((1, 2)) and f([1, 2]) get different keys.
2
Before json.dumps, turn every tuple, at any depth, into something a list can't be, such as {"__tuple__": [...]}. Keep sort_keys=True, so keyword order still doesn't matter.