[Python-ideas] Fwd: Using functools.lru_cache only on some arguments of a function

Franklin? Lee leewangzhong+python at gmail.com
Tue Jan 12 22:45:15 EST 2016


On Tue, Jan 12, 2016 at 9:13 PM, Michael Selik <mike at selik.org> wrote:
> On Tue, Jan 12, 2016 at 6:26 PM Franklin? Lee
> <leewangzhong+python at gmail.com> wrote:
>> Should it be possible to specify a tuple for `key` to transform each
>> arg separately? In your case, you might pass in `(None, lambda x: 0)`
>> to specify that the first parameter shouldn't be transformed, and the
>> second parameter should be considered constant. But that's very
>> confusing: should `None` mean "ignore", or "don't transform" (like
>> `filter`)? Or we can use `False` for "ignore", perhaps.
>
> I think his intention was to mimic the ``key`` argument of sorted, which
> expects a function that takes 1 and only 1 positional argument.

I know, but those three functions expect a sequence of single things,
while `lru_cache` expects several things. (Not exactly a tuple,
because that would be a single thing, but rather a collection of
things.)


> Perhaps it's best to see the exact use case and a few other examples, to get
> a better idea for the specifics, before implementing this feature?
>
>> On Sun, Jan 10, 2016 at 2:03 PM, Michael Selik <mike at selik.org> wrote:
>> > Shouldn't the key function be called with ``key(*args, **kwargs)``?
>>
>> Does `lru_cache` know how to deal with passing regular args as kwargs?
>
>
> Now that you mention it, I realized it treats the two differently.
> ``def foo(x): pass`` would store ``foo(42)`` and ``foo(x=42)`` as different
> entries in the cache.

I feel like, at least ideally, there should be a way for
`update_wrapper`/`wraps` to unpack named arguments, so that wrappers
can truly reflect the params of the functions they wrap. (For example,
when inspecting a function, and by decoding kw-or-positional-args to
their place in `*args`.) It should also be possible to add or remove
args, though I'm not sure how useful that will be. (Also ideally, a
wrapper function would "pass up" its default args to the wrapper.)


More information about the Python-ideas mailing list