Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does it make sense to decorate a @staticmethod with an @lru_cache?

I have in python3:

class MyClass:
    @lru_cache(maxsize=None)
    @staticmethod
    def run_expensive_computation() -> bool:
        return expensive_function("hard_coded_string")

Assuming:

  • expensive_function() itself is NOT cached

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  • "hard_coded_string" will never change so no need to make that as
    input to run_expensive_computation

Is it a waste of time to put @lru_cache(maxsize=None) here if run_expensive_computation takes no inputs ? What will be the key saved in the cache in this case ?

>Solution :

Sure, this is fine and the lru_cache handles this case fine.

A wrapper is used that catches the arguments as *args, **kwargs and a key is extracted from that. In this case, it is just an empty tuple, if you want to see the details, just look at the source. That is the Python version, although, CPython will actually use a C implementation found here

As an aside, in the most recent python versions, >= 3.9, you can use functools.cache for the case where you use maxsize=None, which should be smaller and faster than the LRU cache.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading