Ask Your Question

How to use @lru_cache

asked 2018-05-29 09:41:31 -0500

Sara gravatar image

I am using the notebook of Sagemath 8.1. Is there a way to use the python command @lru_cache in the files with extension .ipynb ? Or in Python 2?(it is the version that is provided in the notebook.)

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2018-05-29 10:59:26 -0500

nbruin gravatar image

As the question points out, this is really about python2. One would expect the answer to be "yes" and it is:

some care is needed to install the required library in sage's python and not in another. So use something like

$ sage -sh
sage-shell$ pip install repoze.lru
edit flag offensive delete link more


I have used: from functools32 import lru_cache @lru_cache() and it works. However my functions takes elements that probably are not hashable. Indeed I get this error TypeError: <class 'sage.combinat.root_system.fundamental_group.fundamentalgroupofextendedaffineweylgroup_class_with_category.element_class'=""> is not hashable Why elements of a group are not hashable? Is there a way to use @lru_cache() for my function?

Sara gravatar imageSara ( 2018-05-29 18:12:03 -0500 )edit

One way would be to implement hashing for the elements you want to hash. Alternatively, you could change the input of your function: it may be the case that you can, for instance, describe your element using a tuple of integers. That is hashable, so if you change your input to that then you can use lru_cache. You could then wrap your cached function in a function that takes the input type you like. In cases like this, it's usually easier and faster to implement your own caching rather than bend to the needs of a decorator.

nbruin gravatar imagenbruin ( 2018-05-30 00:25:00 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2018-05-29 09:41:31 -0500

Seen: 27 times

Last updated: May 29