Ticket #16902: coding_in_cython.html

File coding_in_cython.html, 58.3 KB (added by jdemeyer, 5 years ago)

Built documentation

Line 
1
2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5
6<html xmlns="http://www.w3.org/1999/xhtml">
7  <head>
8    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
9   
10    <title>Coding in Cython &mdash; Sage Developer&#39;s Guide v6.4.beta4</title>
11   
12    <link rel="stylesheet" href="_static/sage.css" type="text/css" />
13    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
14   
15    <script type="text/javascript">
16      var DOCUMENTATION_OPTIONS = {
17        URL_ROOT:    '',
18        VERSION:     '6.4.beta4',
19        COLLAPSE_INDEX: false,
20        FILE_SUFFIX: '.html',
21        HAS_SOURCE:  true
22      };
23    </script>
24    <script type="text/javascript" src="_static/jquery.js"></script>
25    <script type="text/javascript" src="_static/underscore.js"></script>
26    <script type="text/javascript" src="_static/doctools.js"></script>
27    <script type="text/javascript" src="_static/MathJax.js?config=TeX-AMS_HTML-full,../mathjax_sage.js"></script>
28    <script type="text/javascript" src="_static/MathJax.js?config=TeX-AMS_HTML-full,../mathjax_sage.js"></script>
29    <script type="text/javascript" src="_static/MathJax.js?config=TeX-AMS_HTML-full,../mathjax_sage.js"></script>
30    <link rel="shortcut icon" href="_static/favicon.ico"/>
31    <link rel="top" title="Sage Developer&#39;s Guide v6.4.beta4" href="index.html" />
32    <link rel="next" title="Using External Libraries and Interfaces" href="coding_in_other.html" />
33    <link rel="prev" title="Coding in Python for Sage" href="coding_in_python.html" />
34    <link rel="icon" href="_static/sageicon.png" type="image/x-icon" />
35
36  </head>
37  <body>
38    <div class="related">
39      <h3>Navigation</h3>
40      <ul>
41        <li class="right" style="margin-right: 10px">
42          <a href="genindex.html" title="General Index"
43             accesskey="I">index</a></li>
44        <li class="right" >
45          <a href="py-modindex.html" title="Python Module Index"
46             >modules</a> |</li>
47        <li class="right" >
48          <a href="coding_in_other.html" title="Using External Libraries and Interfaces"
49             accesskey="N">next</a> |</li>
50        <li class="right" >
51          <a href="coding_in_python.html" title="Coding in Python for Sage"
52             accesskey="P">previous</a> |</li>
53 
54   
55      <a href="../index.html"><img src="_static/sagelogo.png" style="vertical-align: middle" title="Sage Logo"></a>
56   
57 
58 
59        <li><a href="index.html">Developer&#39;s Guide v6.4.beta4</a> &raquo;</li>
60 
61      </ul>
62    </div> 
63
64    <div class="document">
65      <div class="documentwrapper">
66        <div class="bodywrapper">
67          <div class="body">
68           
69  <div class="section" id="coding-in-cython">
70<span id="chapter-cython"></span><h1>Coding in Cython<a class="headerlink" href="#coding-in-cython" title="Permalink to this headline"></a></h1>
71<p>This chapter discusses Cython, which is a compiled language based on
72Python.  The major advantage it has over Python is that code can be
73much faster (sometimes orders of magnitude) and can directly call
74C and C++ code.  As Cython is essentially a superset of the Python
75language, one often doesn’t make a distinction between Cython and
76Python code in Sage (e.g. one talks of the “Sage Python Library”
77and “Python Coding Conventions”).</p>
78<p>Python is an interpreted language and has no declared data types for
79variables. These features make it easy to write and debug, but Python
80code can sometimes be slow. Cython code can look a lot like Python,
81but it gets translated into C code (often very efficient C code) and
82then compiled. Thus it offers a language which is familiar to Python
83developers, but with the potential for much greater speed. Cython also
84allows Sage developers to interface with C and C++ much easier than
85using the Python C API directly.</p>
86<p>Cython is a compiled version of Python. It was originally based on
87Pyrex but has changed based on what Sage&#8217;s developers needed; Cython
88has been developed in concert with Sage. However, it is an independent
89project now, which is used beyond the scope of Sage. As such, it is a
90young, but developing language, with young, but developing
91documentation. See its web page, <a class="reference external" href="http://www.cython.org/">http://www.cython.org/</a>, for the most
92up-to-date information or check out the
93<a class="reference external" href="http://docs.cython.org/src/userguide/language_basics.html">Language Basics</a>
94to get started immediately.</p>
95<div class="section" id="writing-cython-code-in-sage">
96<h2>Writing Cython Code in Sage<a class="headerlink" href="#writing-cython-code-in-sage" title="Permalink to this headline"></a></h2>
97<p>There are several ways to create and build Cython code in Sage.</p>
98<ol class="arabic">
99<li><p class="first">In the Sage Notebook, begin any cell with <tt class="docutils literal"><span class="pre">%cython</span></tt>. When you
100evaluate that cell,</p>
101<ol class="arabic">
102<li><p class="first">It is saved to a file.</p>
103</li>
104<li><p class="first">Cython is run on it with all the standard Sage libraries
105automatically linked if necessary.</p>
106</li>
107<li><p class="first">The resulting shared library file (<tt class="docutils literal"><span class="pre">.so</span></tt> / <tt class="docutils literal"><span class="pre">.dll</span></tt> /
108<tt class="docutils literal"><span class="pre">.dylib</span></tt>) is then loaded into your running instance of Sage.</p>
109</li>
110<li><p class="first">The functionality defined in that cell is now available for you
111to use in the notebook. Also, the output cell has a link to the C
112program that was compiled to create the <tt class="docutils literal"><span class="pre">.so</span></tt> file.</p>
113</li>
114<li><p class="first">A <tt class="docutils literal"><span class="pre">cpdef</span></tt> or <tt class="docutils literal"><span class="pre">def</span></tt> function, say <tt class="docutils literal"><span class="pre">testfunction</span></tt>, defined in
115a <tt class="docutils literal"><span class="pre">%cython</span></tt> cell in a worksheet can be imported and made available
116in a different <tt class="docutils literal"><span class="pre">%cython</span></tt> cell within the same worksheet by
117importing it as shown below:</p>
118<div class="highlight-python"><pre>%cython
119from __main__ import testfunction</pre>
120</div>
121</li>
122</ol>
123</li>
124<li><p class="first">Create an <tt class="docutils literal"><span class="pre">.spyx</span></tt> file and attach or load it from the command
125line. This is similar to creating a <tt class="docutils literal"><span class="pre">%cython</span></tt> cell in the
126notebook but works completely from the command line (and not from
127the notebook).</p>
128</li>
129<li><p class="first">Create a <tt class="docutils literal"><span class="pre">.pyx</span></tt> file and add it to the Sage library.</p>
130<ol class="arabic simple">
131<li>First, add a listing for the Cython extension to the variable
132<tt class="docutils literal"><span class="pre">ext_modules</span></tt> in the file
133<tt class="docutils literal"><span class="pre">SAGE_ROOT/src/module_list.py</span></tt>. See the
134<tt class="docutils literal"><span class="pre">distutils.extension.Extension</span></tt> class for more information on
135creating a new Cython extension.</li>
136<li>Run <tt class="docutils literal"><span class="pre">sage</span> <span class="pre">-b</span></tt> to rebuild Sage.</li>
137</ol>
138<p>For example, in order to compile
139<tt class="docutils literal"><span class="pre">SAGE_ROOT/src/sage/graphs/chrompoly.pyx</span></tt>, we see the following
140lines in <tt class="docutils literal"><span class="pre">module_list.py</span></tt>:</p>
141<div class="highlight-python"><div class="highlight"><pre><span class="n">Extension</span><span class="p">(</span><span class="s">&#39;sage.graphs.chrompoly&#39;</span><span class="p">,</span>
142          <span class="n">sources</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;sage/graphs/chrompoly.pyx&#39;</span><span class="p">],</span>
143          <span class="n">libraries</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;gmp&#39;</span><span class="p">]),</span>
144</pre></div>
145</div>
146</li>
147</ol>
148</div>
149<div class="section" id="special-pragmas">
150<h2>Special Pragmas<a class="headerlink" href="#special-pragmas" title="Permalink to this headline"></a></h2>
151<p>If Cython code is either attached or loaded as a <tt class="docutils literal"><span class="pre">.spyx</span></tt> file or
152loaded from the notebook as a <tt class="docutils literal"><span class="pre">%cython</span></tt> block, the following
153pragmas are available:</p>
154<ul class="simple">
155<li>clang &#8212; may be either c or c++ indicating whether a C or C++
156compiler should be used.</li>
157<li>clib &#8212; additional libraries to be linked in, the space separated
158list is split and passed to distutils.</li>
159<li>cinclude &#8212; additional directories to search for header files. The
160space separated list is split and passed to distutils.</li>
161<li>cfile &#8211; additional C or C++ files to be compiled</li>
162<li>cargs &#8211; additional parameters passed to the compiler</li>
163</ul>
164<p>For example:</p>
165<div class="highlight-python"><div class="highlight"><pre><span class="c">#clang C++</span>
166<span class="c">#clib givaro</span>
167<span class="c">#cinclude /usr/local/include/</span>
168<span class="c">#cargs -ggdb</span>
169<span class="c">#cfile foo.c</span>
170</pre></div>
171</div>
172</div>
173<div class="section" id="attaching-or-loading-spyx-files">
174<h2>Attaching or Loading .spyx Files<a class="headerlink" href="#attaching-or-loading-spyx-files" title="Permalink to this headline"></a></h2>
175<p>The easiest way to try out Cython without having to learn anything
176about distutils, etc., is to create a file with the extension
177<tt class="docutils literal"><span class="pre">spyx</span></tt>, which stands for &#8220;Sage Pyrex&#8221;:</p>
178<ol class="arabic">
179<li><p class="first">Create a file <tt class="docutils literal"><span class="pre">power2.spyx</span></tt>.</p>
180</li>
181<li><p class="first">Put the following in it:</p>
182<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">is2pow</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
183    <span class="k">while</span> <span class="n">n</span> <span class="o">!=</span> <span class="mi">0</span> <span class="ow">and</span> <span class="n">n</span><span class="o">%</span><span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
184        <span class="n">n</span> <span class="o">=</span> <span class="n">n</span> <span class="o">&gt;&gt;</span> <span class="mi">1</span>
185    <span class="k">return</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">1</span>
186</pre></div>
187</div>
188</li>
189<li><p class="first">Start the Sage command line interpreter and load the <tt class="docutils literal"><span class="pre">spyx</span></tt> file
190(this will fail if you do not have a C compiler installed).</p>
191<div class="highlight-python"><div class="highlight"><pre><span class="gp">sage: </span><span class="n">load</span><span class="p">(</span><span class="s">&quot;power2.spyx&quot;</span><span class="p">)</span>
192<span class="go">Compiling power2.spyx...</span>
193<span class="gp">sage: </span><span class="n">is2pow</span><span class="p">(</span><span class="mi">12</span><span class="p">)</span>
194<span class="go">False</span>
195</pre></div>
196</div>
197</li>
198</ol>
199<p>Note that you can change <tt class="docutils literal"><span class="pre">power2.spyx</span></tt>, then load it again and it
200will be recompiled on the fly. You can also attach <tt class="docutils literal"><span class="pre">power2.spyx</span></tt> so
201it is reloaded whenever you make changes:</p>
202<div class="highlight-python"><div class="highlight"><pre><span class="gp">sage: </span><span class="n">attach</span><span class="p">(</span><span class="s">&quot;power2.spyx&quot;</span><span class="p">)</span>
203</pre></div>
204</div>
205<p>Cython is used for its speed. Here is a timed test on a 2.6 GHz
206Opteron:</p>
207<div class="highlight-python"><div class="highlight"><pre><span class="gp">sage: </span><span class="o">%</span><span class="n">time</span> <span class="p">[</span><span class="n">n</span> <span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="o">^</span><span class="mi">5</span><span class="p">)</span> <span class="k">if</span> <span class="n">is2pow</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
208<span class="go">[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536]</span>
209<span class="go">CPU times: user 0.60 s, sys: 0.00 s, total: 0.60 s</span>
210<span class="go">Wall time: 0.60 s</span>
211</pre></div>
212</div>
213<p>Now, the code in the file <tt class="docutils literal"><span class="pre">power2.spyx</span></tt> is valid Python, and if we
214copy this to a file <tt class="docutils literal"><span class="pre">powerslow.py</span></tt> and load that, we get the
215following:</p>
216<div class="highlight-python"><div class="highlight"><pre><span class="gp">sage: </span><span class="n">load</span><span class="p">(</span><span class="s">&quot;powerslow.py&quot;</span><span class="p">)</span>
217<span class="gp">sage: </span><span class="o">%</span><span class="n">time</span> <span class="p">[</span><span class="n">n</span> <span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="o">^</span><span class="mi">5</span><span class="p">)</span> <span class="k">if</span> <span class="n">is2pow</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
218<span class="go">[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536]</span>
219<span class="go">CPU times: user 1.01 s, sys: 0.04 s, total: 1.05 s</span>
220<span class="go">Wall time: 1.05 s</span>
221</pre></div>
222</div>
223<p>By the way, we could gain even a little more speed with the Cython
224version with a type declaration, by changing <tt class="docutils literal"><span class="pre">def</span> <span class="pre">is2pow(n):</span></tt> to
225<tt class="docutils literal"><span class="pre">def</span> <span class="pre">is2pow(unsigned</span> <span class="pre">int</span> <span class="pre">n):</span></tt>.</p>
226</div>
227<div class="section" id="interrupt-and-signal-handling">
228<span id="section-interrupt"></span><h2>Interrupt and Signal Handling<a class="headerlink" href="#interrupt-and-signal-handling" title="Permalink to this headline"></a></h2>
229<p>When writing Cython code for Sage, special care must be taken to ensure
230the code can be interrupted with <tt class="docutils literal"><span class="pre">CTRL-C</span></tt>.
231Since Cython optimizes for speed,
232Cython normally does not check for interrupts.
233For example, code like the following cannot be interrupted:</p>
234<div class="highlight-python"><div class="highlight"><pre><span class="gp">sage: </span><span class="n">cython</span><span class="p">(</span><span class="s">&#39;while True: pass&#39;</span><span class="p">)</span>  <span class="c"># DON&#39;T DO THIS</span>
235</pre></div>
236</div>
237<p>While this is running, pressing <tt class="docutils literal"><span class="pre">CTRL-C</span></tt> has no effect.  The only
238way out is to kill the Sage process.
239On certain systems, you can still quit Sage by typing <tt class="docutils literal"><span class="pre">CTRL-\</span></tt>
240(sending a Quit signal) instead of <tt class="docutils literal"><span class="pre">CTRL-C</span></tt>.</p>
241<p>Sage provides two related mechanisms to deal with interrupts:</p>
242<ul class="simple">
243<li><a class="reference internal" href="#section-sig-check"><em>Use sig_check()</em></a> if you are writing mixed
244Cython/Python code. Typically this is code with (nested) loops where
245every individual statement takes little time.</li>
246<li><a class="reference internal" href="#section-sig-on"><em>Use sig_on() and sig_off()</em></a> if you are calling
247external C libraries or inside pure Cython code (without any Python
248functions) where even an individual statement, like a library call,
249can take a long time.</li>
250</ul>
251<p>The functions <tt class="docutils literal"><span class="pre">sig_check()</span></tt>, <tt class="docutils literal"><span class="pre">sig_on()</span></tt> and <tt class="docutils literal"><span class="pre">sig_off()</span></tt> can be
252put in all kinds of Cython functions: <tt class="docutils literal"><span class="pre">def</span></tt>, <tt class="docutils literal"><span class="pre">cdef</span></tt> or <tt class="docutils literal"><span class="pre">cpdef</span></tt>.
253You cannot put them in pure Python code (files with extension <tt class="docutils literal"><span class="pre">.py</span></tt>).
254These functions are specific to Sage. To use them, you need to include
255their declarations with:</p>
256<div class="highlight-cython"><div class="highlight"><pre><span class="k">include</span> <span class="s">&quot;sage/ext/interrupt.pxi&quot;</span>
257</pre></div>
258</div>
259<div class="admonition note">
260<p class="first admonition-title">Note</p>
261<p class="last">Cython <tt class="docutils literal"><span class="pre">cdef</span></tt> or <tt class="docutils literal"><span class="pre">cpdef</span></tt> functions with a return type
262(like <tt class="docutils literal"><span class="pre">cdef</span> <span class="pre">int</span> <span class="pre">myfunc():</span></tt>) need to have an
263<a class="reference external" href="http://docs.cython.org/src/userguide/language_basics.html#error-return-values">except value</a>
264to propagate exceptions.
265Remember this whenever you write <tt class="docutils literal"><span class="pre">sig_check()</span></tt> or <tt class="docutils literal"><span class="pre">sig_on()</span></tt>
266inside such a function, otherwise you will see a message like
267<tt class="docutils literal"><span class="pre">Exception</span> <span class="pre">KeyboardInterrupt:</span> <span class="pre">KeyboardInterrupt()</span> <span class="pre">in</span> <span class="pre">&lt;function</span> <span class="pre">name&gt;</span> <span class="pre">ignored</span></tt>.</p>
268</div>
269<div class="section" id="using-sig-check">
270<span id="section-sig-check"></span><h3>Using <tt class="docutils literal"><span class="pre">sig_check()</span></tt><a class="headerlink" href="#using-sig-check" title="Permalink to this headline"></a></h3>
271<p><tt class="docutils literal"><span class="pre">sig_check()</span></tt> can be used to check for pending interrupts.
272If an interrupt happens during the execution of C or Cython code,
273it will be caught by the next <tt class="docutils literal"><span class="pre">sig_check()</span></tt>, the next <tt class="docutils literal"><span class="pre">sig_on()</span></tt>
274or possibly the next Python statement.
275With the latter we mean that certain Python statements also
276check for interrupts, an example of this is the <tt class="docutils literal"><span class="pre">print</span></tt> statement.
277The following loop <em>can</em> be interrupted:</p>
278<div class="highlight-python"><div class="highlight"><pre><span class="gp">sage: </span><span class="n">cython</span><span class="p">(</span><span class="s">&#39;while True: print &quot;Hello&quot;&#39;</span><span class="p">)</span>
279</pre></div>
280</div>
281<p>The typical use case for <tt class="docutils literal"><span class="pre">sig_check()</span></tt> is within tight loops doing
282complicated stuff
283(mixed Python and Cython code, potentially raising exceptions).
284It is reasonably safe to use and gives a lot of control, because in
285your Cython code, a <tt class="docutils literal"><span class="pre">KeyboardInterrupt</span></tt> can <em>only</em> be raised during
286<tt class="docutils literal"><span class="pre">sig_check()</span></tt>:</p>
287<div class="highlight-cython"><div class="highlight"><pre><span class="k">def</span> <span class="nf">sig_check_example</span><span class="p">():</span>
288    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">foo</span><span class="p">:</span>
289        <span class="c"># (one loop iteration which does not take a long time)</span>
290        <span class="n">sig_check</span><span class="p">()</span>
291</pre></div>
292</div>
293<p>This <tt class="docutils literal"><span class="pre">KeyboardInterrupt</span></tt> is treated like any other Python exception
294and can be handled as usual:</p>
295<div class="highlight-cython"><div class="highlight"><pre><span class="k">def</span> <span class="nf">catch_interrupts</span><span class="p">():</span>
296    <span class="k">try</span><span class="p">:</span>
297        <span class="k">while</span> <span class="n">some_condition</span><span class="p">():</span>
298            <span class="n">sig_check</span><span class="p">()</span>
299            <span class="n">do_something</span><span class="p">()</span>
300    <span class="k">except</span> <span class="ne">KeyboardInterrupt</span><span class="p">:</span>
301        <span class="c"># (handle interrupt)</span>
302</pre></div>
303</div>
304<p>Of course, you can also put the <tt class="docutils literal"><span class="pre">try</span></tt>/<tt class="docutils literal"><span class="pre">except</span></tt> inside the loop in
305the example above.</p>
306<p>The function <tt class="docutils literal"><span class="pre">sig_check()</span></tt> is an extremely fast inline function which
307should have no measurable effect on performance.</p>
308</div>
309<div class="section" id="using-sig-on-and-sig-off">
310<span id="section-sig-on"></span><h3>Using <tt class="docutils literal"><span class="pre">sig_on()</span></tt> and <tt class="docutils literal"><span class="pre">sig_off()</span></tt><a class="headerlink" href="#using-sig-on-and-sig-off" title="Permalink to this headline"></a></h3>
311<p>Another mechanism for interrupt handling is the pair of functions
312<tt class="docutils literal"><span class="pre">sig_on()</span></tt> and <tt class="docutils literal"><span class="pre">sig_off()</span></tt>.
313It is more powerful than <tt class="docutils literal"><span class="pre">sig_check()</span></tt> but also a lot more dangerous.
314You should put <tt class="docutils literal"><span class="pre">sig_on()</span></tt> <em>before</em> and <tt class="docutils literal"><span class="pre">sig_off()</span></tt> <em>after</em> any Cython code
315which could potentially take a long time.
316These two <em>must always</em> be called in <strong>pairs</strong>, i.e. every
317<tt class="docutils literal"><span class="pre">sig_on()</span></tt> must be matched by a closing <tt class="docutils literal"><span class="pre">sig_off()</span></tt>.</p>
318<p>In practice your function will probably look like:</p>
319<div class="highlight-cython"><div class="highlight"><pre><span class="k">def</span> <span class="nf">sig_example</span><span class="p">():</span>
320    <span class="c"># (some harmless initialization)</span>
321    <span class="n">sig_on</span><span class="p">()</span>
322    <span class="c"># (a long computation here, potentially calling a C library)</span>
323    <span class="n">sig_off</span><span class="p">()</span>
324    <span class="c"># (some harmless post-processing)</span>
325    <span class="k">return</span> <span class="n">something</span>
326</pre></div>
327</div>
328<p>It is possible to put <tt class="docutils literal"><span class="pre">sig_on()</span></tt> and <tt class="docutils literal"><span class="pre">sig_off()</span></tt> in different functions,
329provided that <tt class="docutils literal"><span class="pre">sig_off()</span></tt> is called before the function which calls
330<tt class="docutils literal"><span class="pre">sig_on()</span></tt> returns.
331The following code is <em>invalid</em>:</p>
332<div class="highlight-cython"><div class="highlight"><pre><span class="c"># INVALID code because we return from function foo()</span>
333<span class="c"># without calling sig_off() first.</span>
334<span class="k">cdef</span> <span class="nf">foo</span><span class="p">():</span>
335    <span class="n">sig_on</span><span class="p">()</span>
336
337<span class="k">def</span> <span class="nf">f1</span><span class="p">():</span>
338    <span class="n">foo</span><span class="p">()</span>
339    <span class="n">sig_off</span><span class="p">()</span>
340</pre></div>
341</div>
342<p>But the following is valid since you cannot call <tt class="docutils literal"><span class="pre">foo</span></tt>
343interactively:</p>
344<div class="highlight-cython"><div class="highlight"><pre><span class="k">cdef</span> <span class="kt">int</span> <span class="nf">foo</span><span class="p">():</span>
345    <span class="n">sig_off</span><span class="p">()</span>
346    <span class="k">return</span> <span class="mf">2</span><span class="o">+</span><span class="mf">2</span>
347
348<span class="k">def</span> <span class="nf">f1</span><span class="p">():</span>
349    <span class="n">sig_on</span><span class="p">()</span>
350    <span class="k">return</span> <span class="n">foo</span><span class="p">()</span>
351</pre></div>
352</div>
353<p>For clarity however, it is best to avoid this.
354One good example where the above makes sense is the <tt class="docutils literal"><span class="pre">new_gen()</span></tt>
355function in <a class="reference internal" href="coding_in_other.html#section-pari-library"><em>The PARI C Library Interface</em></a>.</p>
356<p>A common mistake is to put <tt class="docutils literal"><span class="pre">sig_off()</span></tt> towards the end of a
357function (before the <tt class="docutils literal"><span class="pre">return</span></tt>) when the function has multiple
358<tt class="docutils literal"><span class="pre">return</span></tt> statements.
359So make sure there is a <tt class="docutils literal"><span class="pre">sig_off()</span></tt> before <em>every</em> <tt class="docutils literal"><span class="pre">return</span></tt>
360(and also before every <tt class="docutils literal"><span class="pre">raise</span></tt>).</p>
361<div class="admonition warning">
362<p class="first admonition-title">Warning</p>
363<p>The code inside <tt class="docutils literal"><span class="pre">sig_on()</span></tt> should be pure C or Cython code.
364If you call any Python code or manipulate any Python object
365(even something trivial like <tt class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">[]</span></tt>),
366an interrupt can mess up Python&#8217;s internal state.
367When in doubt, try to use <a class="reference internal" href="#section-sig-check"><em>sig_check()</em></a> instead.</p>
368<p class="last">Also, when an interrupt occurs inside <tt class="docutils literal"><span class="pre">sig_on()</span></tt>, code execution
369immediately stops without cleaning up.
370For example, any memory allocated inside <tt class="docutils literal"><span class="pre">sig_on()</span></tt> is lost.
371See <a class="reference internal" href="#advanced-sig"><em>Advanced Functions</em></a> for ways to deal with this.</p>
372</div>
373<p>When the user presses <tt class="docutils literal"><span class="pre">CTRL-C</span></tt> inside <tt class="docutils literal"><span class="pre">sig_on()</span></tt>, execution will jump back
374to <tt class="docutils literal"><span class="pre">sig_on()</span></tt> (the first one if there is a stack) and <tt class="docutils literal"><span class="pre">sig_on()</span></tt>
375will raise <tt class="docutils literal"><span class="pre">KeyboardInterrupt</span></tt>.  As with <tt class="docutils literal"><span class="pre">sig_check()</span></tt>, this
376exception can be handled in the usual way:</p>
377<div class="highlight-cython"><div class="highlight"><pre><span class="k">def</span> <span class="nf">catch_interrupts</span><span class="p">():</span>
378    <span class="k">try</span><span class="p">:</span>
379        <span class="n">sig_on</span><span class="p">()</span>  <span class="c"># This must be INSIDE the try</span>
380        <span class="c"># (some long computation)</span>
381        <span class="n">sig_off</span><span class="p">()</span>
382    <span class="k">except</span> <span class="ne">KeyboardInterrupt</span><span class="p">:</span>
383        <span class="c"># (handle interrupt)</span>
384</pre></div>
385</div>
386<p>Certain C libraries in Sage are written in a way that they will raise
387Python exceptions:
388libGAP and NTL can raise <tt class="docutils literal"><span class="pre">RuntimeError</span></tt> and PARI can raise <tt class="docutils literal"><span class="pre">PariError</span></tt>.
389These exceptions behave exactly like the <tt class="docutils literal"><span class="pre">KeyboardInterrupt</span></tt>
390in the example above and can be caught by putting the <tt class="docutils literal"><span class="pre">sig_on()</span></tt>
391inside a <tt class="docutils literal"><span class="pre">try</span></tt>/<tt class="docutils literal"><span class="pre">except</span></tt> block.
392See <a class="reference internal" href="#sig-error"><em>Error Handling in C Libraries</em></a> to see how this is implmented.</p>
393<p>It is possible to stack <tt class="docutils literal"><span class="pre">sig_on()</span></tt> and <tt class="docutils literal"><span class="pre">sig_off()</span></tt>.
394If you do this, the effect is exactly the same as if only the outer
395<tt class="docutils literal"><span class="pre">sig_on()</span></tt>/<tt class="docutils literal"><span class="pre">sig_off()</span></tt> was there.  The inner ones will just change
396a reference counter and otherwise do nothing.  Make sure that the number
397of <tt class="docutils literal"><span class="pre">sig_on()</span></tt> calls equal the number of <tt class="docutils literal"><span class="pre">sig_off()</span></tt> calls:</p>
398<div class="highlight-cython"><div class="highlight"><pre><span class="k">def</span> <span class="nf">f1</span><span class="p">():</span>
399    <span class="n">sig_on</span><span class="p">()</span>
400    <span class="n">x</span> <span class="o">=</span> <span class="n">f2</span><span class="p">()</span>
401    <span class="n">sig_off</span><span class="p">()</span>
402
403<span class="k">def</span> <span class="nf">f2</span><span class="p">():</span>
404    <span class="n">sig_on</span><span class="p">()</span>
405    <span class="c"># ...</span>
406    <span class="n">sig_off</span><span class="p">()</span>
407    <span class="k">return</span> <span class="n">ans</span>
408</pre></div>
409</div>
410<p>Extra care must be taken with exceptions raised inside <tt class="docutils literal"><span class="pre">sig_on()</span></tt>.
411The problem is that, if you do not do anything special, the <tt class="docutils literal"><span class="pre">sig_off()</span></tt>
412will never be called if there is an exception.
413If you need to <em>raise</em> an exception yourself, call a <tt class="docutils literal"><span class="pre">sig_off()</span></tt> before it:</p>
414<div class="highlight-cython"><div class="highlight"><pre><span class="k">def</span> <span class="nf">raising_an_exception</span><span class="p">():</span>
415    <span class="n">sig_on</span><span class="p">()</span>
416    <span class="c"># (some long computation)</span>
417    <span class="k">if</span> <span class="p">(</span><span class="n">something_failed</span><span class="p">):</span>
418        <span class="n">sig_off</span><span class="p">()</span>
419        <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s">&quot;something failed&quot;</span><span class="p">)</span>
420    <span class="c"># (some more computation)</span>
421    <span class="n">sig_off</span><span class="p">()</span>
422    <span class="k">return</span> <span class="n">something</span>
423</pre></div>
424</div>
425<p>Alternatively, you can use <tt class="docutils literal"><span class="pre">try</span></tt>/<tt class="docutils literal"><span class="pre">finally</span></tt> which will also catch
426exceptions raised by subroutines inside the <tt class="docutils literal"><span class="pre">try</span></tt>:</p>
427<div class="highlight-cython"><div class="highlight"><pre><span class="k">def</span> <span class="nf">try_finally_example</span><span class="p">():</span>
428    <span class="n">sig_on</span><span class="p">()</span>  <span class="c"># This must be OUTSIDE the try</span>
429    <span class="k">try</span><span class="p">:</span>
430        <span class="c"># (some long computation, potentially raising exceptions)</span>
431        <span class="k">return</span> <span class="n">something</span>
432    <span class="k">finally</span><span class="p">:</span>
433        <span class="n">sig_off</span><span class="p">()</span>
434</pre></div>
435</div>
436<p>If you want to also catch this exception, you need a nested <tt class="docutils literal"><span class="pre">try</span></tt>:</p>
437<div class="highlight-cython"><div class="highlight"><pre><span class="k">def</span> <span class="nf">try_finally_and_catch_example</span><span class="p">():</span>
438    <span class="k">try</span><span class="p">:</span>
439        <span class="n">sig_on</span><span class="p">()</span>
440        <span class="k">try</span><span class="p">:</span>
441            <span class="c"># (some long computation, potentially raising exceptions)</span>
442        <span class="k">finally</span><span class="p">:</span>
443            <span class="n">sig_off</span><span class="p">()</span>
444    <span class="k">except</span> <span class="ne">Exception</span><span class="p">:</span>
445        <span class="k">print</span> <span class="s">&quot;Trouble!Trouble!&quot;</span>
446</pre></div>
447</div>
448<p><tt class="docutils literal"><span class="pre">sig_on()</span></tt> is implemented using the C library call <tt class="docutils literal"><span class="pre">setjmp()</span></tt>
449which takes a very small but still measurable amount of time.
450In very time-critical code, one can conditionally call <tt class="docutils literal"><span class="pre">sig_on()</span></tt>
451and <tt class="docutils literal"><span class="pre">sig_off()</span></tt>:</p>
452<div class="highlight-cython"><div class="highlight"><pre><span class="k">def</span> <span class="nf">conditional_sig_on_example</span><span class="p">(</span><span class="nb">long</span> <span class="n">n</span><span class="p">):</span>
453    <span class="k">if</span> <span class="n">n</span> <span class="o">&gt;</span> <span class="mf">100</span><span class="p">:</span>
454        <span class="n">sig_on</span><span class="p">()</span>
455    <span class="c"># (do something depending on n)</span>
456    <span class="k">if</span> <span class="n">n</span> <span class="o">&gt;</span> <span class="mf">100</span><span class="p">:</span>
457        <span class="n">sig_off</span><span class="p">()</span>
458</pre></div>
459</div>
460<p>This should only be needed if both the check
461(<tt class="docutils literal"><span class="pre">n</span> <span class="pre">&gt;</span> <span class="pre">100</span></tt> in the example) and the code inside the <tt class="docutils literal"><span class="pre">sig_on()</span></tt>
462block take very little time.
463In Sage versions before 4.7, <tt class="docutils literal"><span class="pre">sig_on()</span></tt> was much slower, that&#8217;s why
464there are more checks like this in old code.</p>
465</div>
466<div class="section" id="other-signals">
467<h3>Other Signals<a class="headerlink" href="#other-signals" title="Permalink to this headline"></a></h3>
468<p>Apart from handling interrupts, <tt class="docutils literal"><span class="pre">sig_on()</span></tt> provides more general
469signal handling.
470For example, it handles <a class="reference external" href="../reference/misc/sage/misc/misc.html#sage.misc.misc.alarm" title="(in Sage Reference Manual: Miscellaneous v6.4.beta4)"><tt class="xref py py-func docutils literal"><span class="pre">alarm()</span></tt></a> time-outs by raising an <tt class="docutils literal"><span class="pre">AlarmInterrupt</span></tt>
471(inherited from <tt class="docutils literal"><span class="pre">KeyboardInterrupt</span></tt>) exception.</p>
472<p>If the code inside <tt class="docutils literal"><span class="pre">sig_on()</span></tt> would generate
473a segmentation fault or call the C function <tt class="docutils literal"><span class="pre">abort()</span></tt>
474(or more generally, raise any of SIGSEGV, SIGILL, SIGABRT, SIGFPE, SIGBUS),
475this is caught by the interrupt framework and an exception is raised
476(<tt class="docutils literal"><span class="pre">RuntimeError</span></tt> for SIGABRT, <tt class="docutils literal"><span class="pre">FloatingPointError</span></tt> for SIGFPE
477and the custom exception <tt class="docutils literal"><span class="pre">SignalError</span></tt>, based on <tt class="docutils literal"><span class="pre">BaseException</span></tt>, otherwise):</p>
478<div class="highlight-cython"><div class="highlight"><pre><span class="k">cdef</span> <span class="kr">extern</span> <span class="k">from</span> <span class="s">&#39;stdlib.h&#39;</span><span class="p">:</span>
479    <span class="n">void</span> <span class="n">abort</span><span class="p">()</span>
480
481<span class="k">def</span> <span class="nf">abort_example</span><span class="p">():</span>
482    <span class="n">sig_on</span><span class="p">()</span>
483    <span class="n">abort</span><span class="p">()</span>
484    <span class="n">sig_off</span><span class="p">()</span>
485</pre></div>
486</div>
487<div class="highlight-python"><div class="highlight"><pre><span class="gp">sage: </span><span class="n">abort_example</span><span class="p">()</span>
488<span class="gt">Traceback (most recent call last):</span>
489<span class="c">...</span>
490<span class="nc">RuntimeError</span>: <span class="n-Identifier">Aborted</span>
491</pre></div>
492</div>
493<p>This exception can be handled by a <tt class="docutils literal"><span class="pre">try</span></tt>/<tt class="docutils literal"><span class="pre">except</span></tt> block as explained above.
494A segmentation fault or <tt class="docutils literal"><span class="pre">abort()</span></tt> unguarded by <tt class="docutils literal"><span class="pre">sig_on()</span></tt> would
495simply terminate Sage. This applies only to <tt class="docutils literal"><span class="pre">sig_on()</span></tt>, the function
496<tt class="docutils literal"><span class="pre">sig_check()</span></tt> only deals with interrupts and alarms.</p>
497<p>Instead of <tt class="docutils literal"><span class="pre">sig_on()</span></tt>, there is also a function <tt class="docutils literal"><span class="pre">sig_str(s)</span></tt>,
498which takes a C string <tt class="docutils literal"><span class="pre">s</span></tt> as argument.
499It behaves the same as <tt class="docutils literal"><span class="pre">sig_on()</span></tt>, except that the string <tt class="docutils literal"><span class="pre">s</span></tt>
500will be used as a string for the exception.
501<tt class="docutils literal"><span class="pre">sig_str(s)</span></tt> should still be closed by <tt class="docutils literal"><span class="pre">sig_off()</span></tt>.
502Example Cython code:</p>
503<div class="highlight-cython"><div class="highlight"><pre><span class="k">cdef</span> <span class="kr">extern</span> <span class="k">from</span> <span class="s">&#39;stdlib.h&#39;</span><span class="p">:</span>
504    <span class="n">void</span> <span class="n">abort</span><span class="p">()</span>
505
506<span class="k">def</span> <span class="nf">abort_example_with_sig_str</span><span class="p">():</span>
507    <span class="n">sig_str</span><span class="p">(</span><span class="s">&quot;custom error message&quot;</span><span class="p">)</span>
508    <span class="n">abort</span><span class="p">()</span>
509    <span class="n">sig_off</span><span class="p">()</span>
510</pre></div>
511</div>
512<p>Executing this gives:</p>
513<div class="highlight-python"><div class="highlight"><pre><span class="gp">sage: </span><span class="n">abort_example_with_sig_str</span><span class="p">()</span>
514<span class="gt">Traceback (most recent call last):</span>
515<span class="c">...</span>
516<span class="nc">RuntimeError</span>: <span class="n-Identifier">custom error message</span>
517</pre></div>
518</div>
519<p>With regard to ordinary interrupts (i.e. SIGINT), <tt class="docutils literal"><span class="pre">sig_str(s)</span></tt>
520behaves the same as <tt class="docutils literal"><span class="pre">sig_on()</span></tt>:
521a simple <tt class="docutils literal"><span class="pre">KeyboardInterrupt</span></tt> is raised.</p>
522</div>
523<div class="section" id="error-handling-in-c-libraries">
524<span id="sig-error"></span><h3>Error Handling in C Libraries<a class="headerlink" href="#error-handling-in-c-libraries" title="Permalink to this headline"></a></h3>
525<p>Some C libraries can produce errors and use some sort of callback
526mechanism to report errors: an external error handling function needs
527to be set up which will be called by the C library if an error occurs.</p>
528<p>The function <tt class="docutils literal"><span class="pre">sig_error()</span></tt> can be used to deal with these errors.
529This function may only be called within a <tt class="docutils literal"><span class="pre">sig_on()</span></tt> block (otherwise
530Sage will crash hard) after raising a Python exception. You need to
531use the <a class="reference external" href="http://docs.python.org/2/c-api/exceptions.html">Python/C API</a>
532for this and call <tt class="docutils literal"><span class="pre">sig_error()</span></tt> after calling some variant of
533<tt class="xref py py-func docutils literal"><span class="pre">PyErr_SetObject()</span></tt>. Even within Cython, you cannot use the <tt class="docutils literal"><span class="pre">raise</span></tt>
534statement, because then the <tt class="docutils literal"><span class="pre">sig_error()</span></tt> will never be executed.
535The call to <tt class="docutils literal"><span class="pre">sig_error()</span></tt> will use the <tt class="docutils literal"><span class="pre">sig_on()</span></tt> machinery
536such that the exception will be seen by <tt class="docutils literal"><span class="pre">sig_on()</span></tt>.</p>
537<p>A typical error handler implemented in Cython would look as follows:</p>
538<div class="highlight-cython"><div class="highlight"><pre><span class="k">include</span> <span class="s">&quot;sage/ext/interrupt.pxi&quot;</span>
539<span class="k">from</span> <span class="nn">cpython.exc</span> <span class="k">cimport</span> <span class="n">PyErr_SetString</span>
540
541<span class="k">cdef</span> <span class="kt">void</span> <span class="nf">error_handler</span><span class="p">(</span><span class="n">char</span> <span class="o">*</span><span class="n">msg</span><span class="p">):</span>
542    <span class="n">PyErr_SetString</span><span class="p">(</span><span class="ne">RuntimeError</span><span class="p">,</span> <span class="n">msg</span><span class="p">)</span>
543    <span class="n">sig_error</span><span class="p">()</span>
544</pre></div>
545</div>
546<p>In Sage, this mechanism is used for libGAP, NTL and PARI.</p>
547</div>
548<div class="section" id="advanced-functions">
549<span id="advanced-sig"></span><h3>Advanced Functions<a class="headerlink" href="#advanced-functions" title="Permalink to this headline"></a></h3>
550<p>There are several more specialized functions for dealing with interrupts.
551As mentioned above, <tt class="docutils literal"><span class="pre">sig_on()</span></tt> makes no attempt to clean anything up
552(restore state or freeing memory) when an interrupt occurs.
553In fact, it would be impossible for <tt class="docutils literal"><span class="pre">sig_on()</span></tt> to do that.
554If you want to add some cleanup code, use <tt class="docutils literal"><span class="pre">sig_on_no_except()</span></tt>
555for this. This function behaves <em>exactly</em> like <tt class="docutils literal"><span class="pre">sig_on()</span></tt>, except that
556any exception raised (like <tt class="docutils literal"><span class="pre">KeyboardInterrupt</span></tt> or <tt class="docutils literal"><span class="pre">RuntimeError</span></tt>)
557is not yet passed to Python. Essentially, the exception is there, but
558we prevent Cython from looking for the exception.
559Then <tt class="docutils literal"><span class="pre">cython_check_exception()</span></tt> can be used to make Cython look
560for the exception.</p>
561<p>Normally, <tt class="docutils literal"><span class="pre">sig_on_no_except()</span></tt> returns 1.
562If a signal was caught and an exception raised, <tt class="docutils literal"><span class="pre">sig_on_no_except()</span></tt>
563instead returns 0.
564The following example shows how to use <tt class="docutils literal"><span class="pre">sig_on_no_except()</span></tt>:</p>
565<div class="highlight-cython"><div class="highlight"><pre><span class="k">def</span> <span class="nf">no_except_example</span><span class="p">():</span>
566    <span class="k">if</span> <span class="ow">not</span> <span class="n">sig_on_no_except</span><span class="p">():</span>
567        <span class="c"># (clean up messed up internal state)</span>
568
569        <span class="c"># Make Cython realize that there is an exception.</span>
570        <span class="c"># It will look like the exception was actually raised</span>
571        <span class="c"># by cython_check_exception().</span>
572        <span class="n">cython_check_exception</span><span class="p">()</span>
573    <span class="c"># (some long computation, messing up internal state of objects)</span>
574    <span class="n">sig_off</span><span class="p">()</span>
575</pre></div>
576</div>
577<p>There is also a function <tt class="docutils literal"><span class="pre">sig_str_no_except(s)</span></tt>
578which is analogous to <tt class="docutils literal"><span class="pre">sig_str(s)</span></tt>.</p>
579<div class="admonition note">
580<p class="first admonition-title">Note</p>
581<p class="last">See the file <tt class="file docutils literal"><span class="pre">SAGE_ROOT/src/sage/tests/interrupt.pyx</span></tt>
582for more examples of how to use the various <tt class="docutils literal"><span class="pre">sig_*()</span></tt> functions.</p>
583</div>
584</div>
585<div class="section" id="testing-interrupts">
586<h3>Testing Interrupts<a class="headerlink" href="#testing-interrupts" title="Permalink to this headline"></a></h3>
587<p>When writing <a class="reference internal" href="coding_basics.html#section-docstrings"><em>Documentation Strings</em></a>,
588one sometimes wants to check that certain code can be interrupted in a clean way.
589The best way to do this is to use <a class="reference external" href="../reference/misc/sage/misc/misc.html#sage.misc.misc.alarm" title="(in Sage Reference Manual: Miscellaneous v6.4.beta4)"><tt class="xref py py-func docutils literal"><span class="pre">alarm()</span></tt></a>.</p>
590<p>The following is an example of a doctest demonstrating that
591the function <a class="reference external" href="../reference/misc/sage/rings/arith.html#sage.rings.arith.factor" title="(in Sage Reference Manual: Miscellaneous v6.4.beta4)"><tt class="xref py py-func docutils literal"><span class="pre">factor()</span></tt></a> can be interrupted:</p>
592<div class="highlight-python"><div class="highlight"><pre><span class="gp">sage: </span><span class="n">alarm</span><span class="p">(</span><span class="mf">0.5</span><span class="p">);</span> <span class="n">factor</span><span class="p">(</span><span class="mi">10</span><span class="o">^</span><span class="mi">1000</span> <span class="o">+</span> <span class="mi">3</span><span class="p">)</span>
593<span class="gt">Traceback (most recent call last):</span>
594<span class="c">...</span>
595<span class="nc">AlarmInterrupt</span>
596</pre></div>
597</div>
598</div>
599<div class="section" id="releasing-the-global-interpreter-lock-gil">
600<h3>Releasing the Global Interpreter Lock (GIL)<a class="headerlink" href="#releasing-the-global-interpreter-lock-gil" title="Permalink to this headline"></a></h3>
601<p>All the functions related to interrupt and signal handling do not
602require the
603<a class="reference external" href="http://docs.cython.org/src/userguide/external_C_code.html#acquiring-and-releasing-the-gil">Python GIL</a>
604(if you don&#8217;t know what this means, you can safely ignore this section),
605they are declared <tt class="docutils literal"><span class="pre">nogil</span></tt>.
606This means that they can be used in Cython code inside <tt class="docutils literal"><span class="pre">with</span> <span class="pre">nogil</span></tt>
607blocks. If <tt class="docutils literal"><span class="pre">sig_on()</span></tt> needs to raise an exception, the GIL is
608temporarily acquired internally.</p>
609<p>If you use C libraries without the GIL and you want to raise an exception
610after <a class="reference internal" href="#sig-error"><em>sig_error()</em></a>, remember to acquire the GIL
611while raising the exception. Within Cython, you can use a
612<a class="reference external" href="http://docs.cython.org/src/userguide/external_C_code.html#acquiring-the-gil">with gil context</a>.</p>
613<div class="admonition warning">
614<p class="first admonition-title">Warning</p>
615<p class="last">The GIL should never be released or acquired inside a <tt class="docutils literal"><span class="pre">sig_on()</span></tt>
616block. If you want to use a <tt class="docutils literal"><span class="pre">with</span> <span class="pre">nogil</span></tt> block, put both
617<tt class="docutils literal"><span class="pre">sig_on()</span></tt> and <tt class="docutils literal"><span class="pre">sig_off()</span></tt> inside that block. When in doubt,
618choose to use <tt class="docutils literal"><span class="pre">sig_check()</span></tt> instead, which is always safe to use.</p>
619</div>
620</div>
621</div>
622<div class="section" id="unpickling-cython-code">
623<h2>Unpickling Cython Code<a class="headerlink" href="#unpickling-cython-code" title="Permalink to this headline"></a></h2>
624<p>Pickling for Python classes and extension classes, such as Cython, is different.
625This is discussed in the <a class="reference external" href="http://docs.python.org/library/pickle.html#pickle-protocol">Python pickling documentation</a>. For the unpickling of
626extension classes you need to write a <tt class="xref py py-meth docutils literal"><span class="pre">__reduce__()</span></tt> method which typically
627returns a tuple <tt class="docutils literal"><span class="pre">(f,</span> <span class="pre">args,</span> <span class="pre">...)</span></tt> such that <tt class="docutils literal"><span class="pre">f(*args)</span></tt> returns (a copy of) the
628original object. As an example, the following code snippet is the
629<tt class="xref py py-meth docutils literal"><span class="pre">__reduce__()</span></tt> method from
630<a class="reference external" href="../reference/rings_standard/sage/rings/integer.html#sage.rings.integer.Integer" title="(in Sage Reference Manual: Standard Commutative Rings v6.4.beta4)"><tt class="xref py py-class docutils literal"><span class="pre">sage.rings.integer.Integer</span></tt></a>:</p>
631<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">__reduce__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
632    <span class="sd">&#39;&#39;&#39;</span>
633<span class="sd">    This is used when pickling integers.</span>
634
635<span class="sd">    EXAMPLES::</span>
636
637<span class="sd">        sage: n = 5</span>
638<span class="sd">        sage: t = n.__reduce__(); t</span>
639<span class="sd">        (&lt;built-in function make_integer&gt;, (&#39;5&#39;,))</span>
640<span class="sd">        sage: t[0](*t[1])</span>
641<span class="sd">        5</span>
642<span class="sd">        sage: loads(dumps(n)) == n</span>
643<span class="sd">        True</span>
644<span class="sd">    &#39;&#39;&#39;</span>
645    <span class="c"># This single line below took me HOURS to figure out.</span>
646    <span class="c"># It is the *trick* needed to pickle Cython extension types.</span>
647    <span class="c"># The trick is that you must put a pure Python function</span>
648    <span class="c"># as the first argument, and that function must return</span>
649    <span class="c"># the result of unpickling with the argument in the second</span>
650    <span class="c"># tuple as input. All kinds of problems happen</span>
651    <span class="c"># if we don&#39;t do this.</span>
652    <span class="k">return</span> <span class="n">sage</span><span class="o">.</span><span class="n">rings</span><span class="o">.</span><span class="n">integer</span><span class="o">.</span><span class="n">make_integer</span><span class="p">,</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">str</span><span class="p">(</span><span class="mi">32</span><span class="p">),)</span>
653</pre></div>
654</div>
655</div>
656</div>
657
658
659          </div>
660        </div>
661      </div>
662      <div class="sphinxsidebar">
663        <div class="sphinxsidebarwrapper">
664            <h3><a href="index.html">Table Of Contents</a></h3>
665            <ul>
666<li><a class="reference internal" href="#">Coding in Cython</a><ul>
667<li><a class="reference internal" href="#writing-cython-code-in-sage">Writing Cython Code in Sage</a></li>
668<li><a class="reference internal" href="#special-pragmas">Special Pragmas</a></li>
669<li><a class="reference internal" href="#attaching-or-loading-spyx-files">Attaching or Loading .spyx Files</a></li>
670<li><a class="reference internal" href="#interrupt-and-signal-handling">Interrupt and Signal Handling</a><ul>
671<li><a class="reference internal" href="#using-sig-check">Using <tt class="docutils literal"><span class="pre">sig_check()</span></tt></a></li>
672<li><a class="reference internal" href="#using-sig-on-and-sig-off">Using <tt class="docutils literal"><span class="pre">sig_on()</span></tt> and <tt class="docutils literal"><span class="pre">sig_off()</span></tt></a></li>
673<li><a class="reference internal" href="#other-signals">Other Signals</a></li>
674<li><a class="reference internal" href="#error-handling-in-c-libraries">Error Handling in C Libraries</a></li>
675<li><a class="reference internal" href="#advanced-functions">Advanced Functions</a></li>
676<li><a class="reference internal" href="#testing-interrupts">Testing Interrupts</a></li>
677<li><a class="reference internal" href="#releasing-the-global-interpreter-lock-gil">Releasing the Global Interpreter Lock (GIL)</a></li>
678</ul>
679</li>
680<li><a class="reference internal" href="#unpickling-cython-code">Unpickling Cython Code</a></li>
681</ul>
682</li>
683</ul>
684
685            <h4>Previous topic</h4>
686            <p class="topless"><a href="coding_in_python.html"
687                                  title="previous chapter">Coding in Python for Sage</a></p>
688            <h4>Next topic</h4>
689            <p class="topless"><a href="coding_in_other.html"
690                                  title="next chapter">Using External Libraries and Interfaces</a></p>
691            <h3>This Page</h3>
692            <ul class="this-page-menu">
693              <li><a href="_sources/coding_in_cython.txt"
694                     rel="nofollow">Show Source</a></li>
695            </ul>
696          <div id="searchbox" style="display: none">
697            <h3>Quick search</h3>
698              <form class="search" action="search.html" method="get">
699                <input type="text" name="q" size="18" />
700                <!-- The shading of the "Go" button should be consistent -->
701                <!-- with the colour of the header and footer. See the file -->
702                <!-- doc/common/themes/sage/theme.conf for colours used by -->
703                <!-- the Sage theme. -->
704                <input type="submit" style="background-color: #B8B9F6" value="Go" />
705                <input type="hidden" name="check_keywords" value="yes" />
706                <input type="hidden" name="area" value="default" />
707              </form>
708              <p class="searchtip" style="font-size: 90%">
709              Enter search terms or a module, class or function name.
710              </p>
711          </div>
712          <script type="text/javascript">$('#searchbox').show(0);</script>
713        </div>
714      </div>
715      <div class="clearer"></div>
716    </div>
717    <div class="related">
718      <h3>Navigation</h3>
719      <ul>
720        <li class="right" style="margin-right: 10px">
721          <a href="genindex.html" title="General Index"
722             >index</a></li>
723        <li class="right" >
724          <a href="py-modindex.html" title="Python Module Index"
725             >modules</a> |</li>
726        <li class="right" >
727          <a href="coding_in_other.html" title="Using External Libraries and Interfaces"
728             >next</a> |</li>
729        <li class="right" >
730          <a href="coding_in_python.html" title="Coding in Python for Sage"
731             >previous</a> |</li>
732 
733   
734      <a href="../index.html"><img src="_static/sagelogo.png" style="vertical-align: middle" title="Sage Logo"></a>
735   
736 
737 
738        <li><a href="index.html">Developer&#39;s Guide v6.4.beta4</a> &raquo;</li>
739 
740      </ul>
741    </div>
742   
743    <div class="footer">
744        &copy; Copyright 2005--2014, The Sage Development Team.
745      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.2.
746    </div>
747    <script type="text/javascript">
748/*global jQuery, window */
749/* Sphinx sidebar toggle.  Putting this code at the end of the body
750 * enables the toggle for the live, static, and offline docs.  Note:
751 * sage.misc.html.math_parse() eats jQuery's dollar-sign shortcut. */
752var jq = jQuery;
753jq(document).ready(function () {
754    var bar, bod, bg, fg, key, tog, wid_old, wid_new, resize, get_state, set_state;
755    bod = jq('div.bodywrapper');
756    bar = jq('div.sphinxsidebar');
757    tog = jq('<div class="sphinxsidebartoggle"></div>');
758
759    /* Delayed resize helper.  Not perfect but good enough. */
760    resize = function () {
761        setTimeout(function () {
762            tog.height(bod.height());
763        }, 100);
764    };
765    jq(window).resize(function () {
766        resize();
767    });
768
769    /* Setup and add the toggle. See Sphinx v0.5.1 default.css. */
770    fg = jq('div.sphinxsidebar p a').css('color') || 'rgb(152, 219, 204)';
771    bg = jq('div.document').css('background-color') || 'rgb(28, 78, 99)';
772    wid_old = '230px';
773    wid_new = '5px';
774    tog.css('background-color', bg)
775        .css('border-width', '0px')
776        .css('border-right', wid_new + ' ridge ' + bg)
777        .css('cursor', 'pointer')
778        .css('position', 'absolute')
779        .css('left', '-' + wid_new)
780        .css('top', '0px')
781        .css('width', wid_new);
782    bod.css('position', 'relative');
783    bod.prepend(tog);
784    resize();
785
786    /* Cookie helpers. */
787    key = 'sphinxsidebar=';
788    set_state = function (s) {
789        var date = new Date();
790        /* Expiry in 7 days. */
791        date.setTime(date.getTime() + (7 * 24 * 3600 * 1000));
792        document.cookie = key + encodeURIComponent(s) + '; expires=' +
793            date.toUTCString() + '; path=/';
794    };
795    get_state = function () {
796        var i, c, crumbs = document.cookie.split(';');
797        for (i = 0; i < crumbs.length; i += 1) {
798            c = crumbs[i].replace(/^\s+/, '');
799            if (c.indexOf(key) === 0) {
800                return decodeURIComponent(c.substring(key.length, c.length));
801            }
802        }
803        return null;
804    };
805
806    /* Event handlers. */
807    tog.mouseover(function (ev) {
808        tog.css('border-right-color', fg);
809    }).mouseout(function (ev) {
810        tog.css('border-right-color', bg);
811    }).click(function (ev) {
812        if (bod.hasClass('wide')) {
813            bod.removeClass('wide');
814            bod.css('margin-left', wid_old);
815            bar.css('width', wid_old);
816            bar.show();
817            set_state('visible');
818        } else {
819            set_state('hidden');
820            bar.hide();
821            bar.css('width', '0px');
822            bod.css('margin-left', wid_new);
823            bod.addClass('wide');
824        }
825        resize();
826    });
827
828    /* Hide the normally visible sidebar? */
829    if (get_state() === 'hidden') {
830        tog.trigger('click');
831    } else {
832        set_state('visible');
833    }
834});
835    </script>
836  </body>
837</html>