Ask Your Question
0

How to use @lru_cache

asked 2018-05-29 16:41:31 +0100

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
0

answered 2018-05-29 17:59:26 +0100

nbruin gravatar image

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

https://stackoverflow.com/questions/1...

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

Comments

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-30 01:12:03 +0100 )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 07:25:00 +0100 )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

Stats

Asked: 2018-05-29 16:41:31 +0100

Seen: 651 times

Last updated: May 29 '18