save definitions

i like this post (click again to cancel)
0
i dont like this post (click again to cancel)

Hello,

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.

Thanks.-.

asked Mar 16 '12

emiliocba gravatar image emiliocba flag of Argentina
43 5
i like this answer (click again to cancel)
2
i dont like this answer (click again to cancel) emiliocba has selected this answer as correct

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.

Example:

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)
25

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

link

posted Mar 16 '12

Simon King gravatar image Simon King
376 2 11

Your answer

Please start posting your answer anonymously - your answer will be saved within the current session and published after you log in or create a new account. Please try to give a substantial answer, for discussions, please use comments and please do remember to vote (after you log in)!
[hide preview]

Question tools

Tags:

Stats:

Asked: Mar 16 '12

Seen: 49 times

Last updated: Mar 16 '12

powered by ASKBOT version 0.7.22
Copyright Sage, 2010. Some rights reserved under creative commons license.