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

Michael Selik mike at selik.org
Thu Dec 31 00:10:51 EST 2015


On Tue, Dec 29, 2015 at 2:14 AM Franklin? Lee <leewangzhong+python at gmail.com>
wrote:

> On Sat, Dec 12, 2015 at 1:34 PM, Michael Selik <mike at selik.org> wrote:
> > On Fri, Dec 11, 2015, 8:20 PM Franklin? Lee <
> leewangzhong+python at gmail.com>
> > wrote:
>
> This whole thing is probably best implemented as two separate functions
> > rather than using a closure, depending on how intertwined the code paths
> are
> > for the shortcut/non-shortcut versions.
>
> I like the closure because it has semantic ownership: the inner
> function is a worker for the outer function.
>

True, a closure has better encapsulation, making it less likely someone
will misuse the helper function. On the other hand, that means there's less
modularity and it would be difficult for someone to use the inner function.
It's hard to know the right choice without seeing the exact problem the
original author was working on.


> >> On Fri, Dec 11, 2015 at 8:01 PM, Franklin? Lee
> >> <leewangzhong+python at gmail.com> wrote:
> >> > 1. Rewrite your recursive function so that the partial state is a
> >> > nonlocal variable (in the closure), and memoize the recursive part.
> >
> > I'd flip the rare-case to the except block and put the normal-case in the
> > try block. I believe this will be more compute-efficient and more
> readable.
>
> The rare case is in the except block, though.
>

You're correct. Sorry, I somehow misinterpreted the comment, "# To trigger
the exception the first time" as indicating that code path would run only
once.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151231/72682e2d/attachment-0001.html>


More information about the Python-ideas mailing list