Ask Your Question

save definitions

asked 2012-03-16 01:53:13 -0500

emiliocba gravatar image


I want to use save a definition in the interactive shell. For example, I define

sage: def F(m):
....:     return 2*m

I put

sage: save(F,'function')

but it doesn't work. How can I do to save this definition and then load to work with it.


edit retag flag offensive close merge delete


niles gravatar imageniles ( 2012-03-16 07:48:48 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2012-03-16 04:20:35 -0500

Simon King gravatar image

Saving functions is a general problem with Python (and Python is Sage's language). But Sage provides a partial solution in the modules sage.misc.fpickle. That module contains a function pickle_function, that translates a given function into a string (and then you can save the string). And it also contains a function unpickle_function, that translates that string into a function.


sage: from sage.misc.fpickle import pickle_function, unpickle_function
sage: def my_func(x): return x^2
sage: tmp = tmp_filename()
sage: save(pickle_function(my_func), tmp)
sage: recovered_function = unpickle_function(load(tmp))
sage: recovered_function(5)

pickle_function does have limitations (as explained in the docs), but perhaps it is enough for your application?

edit flag offensive delete link more

Your Answer

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

Add Answer

Question Tools


Asked: 2012-03-16 01:53:13 -0500

Seen: 142 times

Last updated: Mar 16 '12