ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Fri, 16 Mar 2012 13:48:48 +0100save definitionshttps://ask.sagemath.org/question/8794/save-definitions/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.-.
Fri, 16 Mar 2012 07:53:13 +0100https://ask.sagemath.org/question/8794/save-definitions/Comment by niles for <p>Hello,</p>
<p>I want to use save a definition in the interactive shell. For example, I define</p>
<pre><code>sage: def F(m):
....: return 2*m
....:
</code></pre>
<p>I put </p>
<pre><code>sage: save(F,'function')
</code></pre>
<p>but it doesn't work. How can I do to save this definition and then load to work with it.</p>
<p>Thanks.-.</p>
https://ask.sagemath.org/question/8794/save-definitions/?comment=20116#post-id-20116This looks like a duplicate of http://ask.sagemath.org/question/1229/how-to-save-a-function-in-sageFri, 16 Mar 2012 13:48:48 +0100https://ask.sagemath.org/question/8794/save-definitions/?comment=20116#post-id-20116Answer by Simon King for <p>Hello,</p>
<p>I want to use save a definition in the interactive shell. For example, I define</p>
<pre><code>sage: def F(m):
....: return 2*m
....:
</code></pre>
<p>I put </p>
<pre><code>sage: save(F,'function')
</code></pre>
<p>but it doesn't work. How can I do to save this definition and then load to work with it.</p>
<p>Thanks.-.</p>
https://ask.sagemath.org/question/8794/save-definitions/?answer=13366#post-id-13366Saving 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?Fri, 16 Mar 2012 10:20:35 +0100https://ask.sagemath.org/question/8794/save-definitions/?answer=13366#post-id-13366