disable `functools.lru_cache` from inside function

2024/10/3 15:38:56

I want to have a function that can use functools.lru_cache, but not by default. I am looking for a way to use a function parameter that can be used to disable the lru_cache. Currently, I have a two versions of the function, one with lru_cache and one without. Then I have another function that wraps these with a parameter that can be used to control which function is used

def _no_cache(foo):print('_no_cache')return 1@lru_cache()
def _with_cache(foo):print('_with_cache')return 0def cache(foo, use_cache=False):if use_cache:return _with_cache(foo)return _no_cache(foo)

Is there a simpler way to do this?

Answer

You can't disable the cache from inside the decorated function. However, you can simplify your code a bit by accessing the function directly via the __wrapped__ attribute.

From the documentation:

The original underlying function is accessible through the __wrapped__attribute. This is useful for introspection, for bypassing the cache,or for rewrapping the function with a different cache.

Demo:

from functools import lru_cache@lru_cache()
def f(arg):print(f"called with {arg}")return arg    def call(arg, use_cache=False):if use_cache:return f(arg)return f.__wrapped__(arg)call(1)
call(1, True)
call(2, True)
call(1, True)

Output:

called with 1
called with 1
called with 2
https://en.xdnf.cn/q/70663.html

Related Q&A

How to clear tf.flags?

If I run this code twice:tf.flags.DEFINE_integer("batch_size", "2", "batch size for training")I will get this error:DuplicateFlagError: The flag batch_size is defined twic…

Stochastic Optimization in Python

I am trying to combine cvxopt (an optimization solver) and PyMC (a sampler) to solve convex stochastic optimization problems. For reference, installing both packages with pip is straightforward: pip in…

Pandas convert yearly to monthly

Im working on pulling financial data, in which some is formatted in yearly and other is monthly. My model will need all of it monthly, therefore I need that same yearly value repeated for each month. …

Firebase database data to R

I have a database in Google Firebase that has streaming sensor data. I have a Shiny app that needs to read this data and map the sensors and their values.I am trying to pull the data from Firebase into…

Django 1.8 Migrations - NoneType object has no attribute _meta

Attempting to migrate a project from Django 1.7 to 1.8. After wrestling with code errors, Im able to get migrations to run. However, when I try to migrate, Im given the error "NoneType object has …

Manage dependencies of git submodules with poetry

We have a repository app-lib that is used as sub-module in 4 other repos and in each I have to add all dependencies for the sub-module. So if I add/remove a dependency in app-lib I have to adjust all o…

Create Boxplot Grouped By Column

I have a Pandas DataFrame, df, that has a price column and a year column. I want to create a boxplot after grouping the rows based on their year. Heres an example: import pandas as pd temp = pd.DataF…

How can I configure gunicorn to use a consistent error log format?

I am using Gunicorn in front of a Python Flask app. I am able to configure the access log format using the --access-log-format command line parameter when I run gunicorn. But I cant figure out how to c…

Implementing seq2seq with beam search

Im now implementing seq2seq model based on the example code that tensorflow provides. And I want to get a top-5 decoder outputs to do a reinforcement learning.However, they implemented translation mode…

Pandas Random Weighted Choice

I would like to randomly select a value in consideration of weightings using Pandas.df:0 1 2 3 4 5 0 40 5 20 10 35 25 1 24 3 12 6 21 15 2 72 9 36 18 63 45 3 8 1 4 2 7 5 4 16 2 8 4…