1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Function memoization, passing around precomputed values [closed]

Discussão em 'Python' iniciado por Stack, Setembro 16, 2024.

  1. Stack

    Stack Membro Participativo

    I have a function like this in my library, which depends on a large subset of the inputs being pre-calculated:

    @cache
    def f(n, precompute):
    if n < len(precompute):
    return precompute[n]

    # recursive calculations, which are memoized on return
    return some_compute(f(n-1, precompute))


    What's the most user-friendly way to pass around a precomputed list while using memoizing functools.cache, without caching the precompute?

    My ideas:

    • Just make precompute a global/outer scope variable (impure, global variable has to exist in the module beforehand How to create module-wide variables in Python?)
    • Make precompute a function attribute to use it as an "argument" bypassing caching (works because the function is an object)
    • Write a special memoziation decorator that is only based on the first argument (suggested in Caching Python function results using only subset of arguments as identifier)
    • Turn it into a class so precomputed can be an instance attribute or class attribute (this is what sympy.sieve does)
    • Load cache(f) with the values of precompute. My thinking is that this is less efficient as the cache will be a dictionary, while precompute is a simple list of size 10^7
    • Create an inner helper recursive function with one argument that uses precompute in the outer scope (I don't think works across multiple outer calls because the inner falls out of scope)

    Continue reading...

Compartilhe esta Página