Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_make_key function in Python's LRU cache code

Tags:

python

lru

I am looking into Python's Least Recently Used (LRU) cache implementation here.

Can someone please explain what the _make_key function is doing?

def _make_key(args, kwds, typed,
             kwd_mark = (object(),),
             fasttypes = {int, str, frozenset, type(None)},
             sorted=sorted, tuple=tuple, type=type, len=len):
    'Make a cache key from optionally typed positional and keyword arguments'
    key = args
    if kwds:
        sorted_items = sorted(kwds.items())
        key += kwd_mark
        for item in sorted_items:
            key += item
    if typed:
        key += tuple(type(v) for v in args)
        if kwds:
            key += tuple(type(v) for k, v in sorted_items)
    elif len(key) == 1 and type(key[0]) in fasttypes:
        return key[0]
    return _HashedSeq(key)
like image 895
devd Avatar asked Nov 26 '25 20:11

devd


1 Answers

Summary

The _make_key() function flattens the arguments into a compact tuple that can be used to determine whether the arguments for two calls are the same.

Generated keys

The call f(10, 20, x=30, y=40) and f(10, 20, y=40, x=30) both have the same key:

(10, 20, <object object at 0x7fae2bb25040>, 'x', 30, 'y', 40)

The 10 and 20 positional arguments are record in the order specified.

The kwd_mark separates the keyword arguments from the positional arguments.

The keyword arguments are sorted so that x=30, y=40 is recognized as being the same as y=40, x=30.

If typed is true, then the key also records the argument types:

(10, 20,                            # positional args
<object object at 0x7fae2bb25040>,  # kwd_mark
'x', 30, 'y', 40,                   # keyword args
<class 'int'>, <class 'int'>,       # types of the args  
<class 'int'>, <class 'int'>)
like image 157
Raymond Hettinger Avatar answered Nov 29 '25 08:11

Raymond Hettinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!