Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v9 / html / python / ext / dnt-basics.html
CommitLineData
920dae64
AT
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<html>
3<head>
4<link rel="STYLESHEET" href="ext.css" type='text/css' />
5<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
6<link rel='start' href='../index.html' title='Python Documentation Index' />
7<link rel="first" href="ext.html" title='Extending and Embedding the Python Interpreter' />
8<link rel='contents' href='contents.html' title="Contents" />
9<link rel='last' href='about.html' title='About this document...' />
10<link rel='help' href='about.html' title='About this document...' />
11<link rel="next" href="dnt-type-methods.html" />
12<link rel="prev" href="defining-new-types.html" />
13<link rel="parent" href="defining-new-types.html" />
14<link rel="next" href="node22.html" />
15<meta name='aesop' content='information' />
16<title>2.1 The Basics
17</title>
18</head>
19<body>
20<DIV CLASS="navigation">
21<div id='top-navigation-panel' xml:id='top-navigation-panel'>
22<table align="center" width="100%" cellpadding="0" cellspacing="2">
23<tr>
24<td class='online-navigation'><a rel="prev" title="2. Defining New Types"
25 href="defining-new-types.html"><img src='../icons/previous.png'
26 border='0' height='32' alt='Previous Page' width='32' /></A></td>
27<td class='online-navigation'><a rel="parent" title="2. Defining New Types"
28 href="defining-new-types.html"><img src='../icons/up.png'
29 border='0' height='32' alt='Up One Level' width='32' /></A></td>
30<td class='online-navigation'><a rel="next" title="2.1.1 Adding data and"
31 href="node22.html"><img src='../icons/next.png'
32 border='0' height='32' alt='Next Page' width='32' /></A></td>
33<td align="center" width="100%">Extending and Embedding the Python Interpreter</td>
34<td class='online-navigation'><a rel="contents" title="Table of Contents"
35 href="contents.html"><img src='../icons/contents.png'
36 border='0' height='32' alt='Contents' width='32' /></A></td>
37<td class='online-navigation'><img src='../icons/blank.png'
38 border='0' height='32' alt='' width='32' /></td>
39<td class='online-navigation'><img src='../icons/blank.png'
40 border='0' height='32' alt='' width='32' /></td>
41</tr></table>
42<div class='online-navigation'>
43<b class="navlabel">Previous:</b>
44<a class="sectref" rel="prev" href="defining-new-types.html">2. Defining New Types</A>
45<b class="navlabel">Up:</b>
46<a class="sectref" rel="parent" href="defining-new-types.html">2. Defining New Types</A>
47<b class="navlabel">Next:</b>
48<a class="sectref" rel="next" href="node22.html">2.1.1 Adding data and</A>
49</div>
50<hr /></div>
51</DIV>
52<!--End of Navigation Panel-->
53
54<H1><A NAME="SECTION004100000000000000000"></A><A NAME="dnt-basics"></A>
55<BR>
562.1 The Basics
57
58</H1>
59
60<P>
61The Python runtime sees all Python objects as variables of type
62<tt class="ctype">PyObject*</tt>. A <tt class="ctype">PyObject</tt> is not a very magnificent
63object - it just contains the refcount and a pointer to the object's
64``type object''. This is where the action is; the type object
65determines which (C) functions get called when, for instance, an
66attribute gets looked up on an object or it is multiplied by another
67object. These C functions are called ``type methods'' to distinguish
68them from things like <code>[].append</code> (which we call ``object
69methods'').
70
71<P>
72So, if you want to define a new object type, you need to create a new
73type object.
74
75<P>
76This sort of thing can only be explained by example, so here's a
77minimal, but complete, module that defines a new type:
78
79<P>
80<div class="verbatim">
81<pre>#include &lt;Python.h&gt;
82
83typedef struct {
84 PyObject_HEAD
85 /* Type-specific fields go here. */
86} noddy_NoddyObject;
87
88static PyTypeObject noddy_NoddyType = {
89 PyObject_HEAD_INIT(NULL)
90 0, /*ob_size*/
91 "noddy.Noddy", /*tp_name*/
92 sizeof(noddy_NoddyObject), /*tp_basicsize*/
93 0, /*tp_itemsize*/
94 0, /*tp_dealloc*/
95 0, /*tp_print*/
96 0, /*tp_getattr*/
97 0, /*tp_setattr*/
98 0, /*tp_compare*/
99 0, /*tp_repr*/
100 0, /*tp_as_number*/
101 0, /*tp_as_sequence*/
102 0, /*tp_as_mapping*/
103 0, /*tp_hash */
104 0, /*tp_call*/
105 0, /*tp_str*/
106 0, /*tp_getattro*/
107 0, /*tp_setattro*/
108 0, /*tp_as_buffer*/
109 Py_TPFLAGS_DEFAULT, /*tp_flags*/
110 "Noddy objects", /* tp_doc */
111};
112
113static PyMethodDef noddy_methods[] = {
114 {NULL} /* Sentinel */
115};
116
117#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
118#define PyMODINIT_FUNC void
119#endif
120PyMODINIT_FUNC
121initnoddy(void)
122{
123 PyObject* m;
124
125 noddy_NoddyType.tp_new = PyType_GenericNew;
126 if (PyType_Ready(&amp;noddy_NoddyType) &lt; 0)
127 return;
128
129 m = Py_InitModule3("noddy", noddy_methods,
130 "Example module that creates an extension type.");
131
132 Py_INCREF(&amp;noddy_NoddyType);
133 PyModule_AddObject(m, "Noddy", (PyObject *)&amp;noddy_NoddyType);
134}
135</pre>
136<div class="footer">
137<a href="noddy.txt" type="text/plain">Download as text (original file name: <span class="file">noddy.c</span>).</a>
138</div></div>
139
140<P>
141Now that's quite a bit to take in at once, but hopefully bits will
142seem familiar from the last chapter.
143
144<P>
145The first bit that will be new is:
146
147<P>
148<div class="verbatim"><pre>
149typedef struct {
150 PyObject_HEAD
151} noddy_NoddyObject;
152</pre></div>
153
154<P>
155This is what a Noddy object will contain--in this case, nothing more
156than every Python object contains, namely a refcount and a pointer to a type
157object. These are the fields the <code>PyObject_HEAD</code> macro brings
158in. The reason for the macro is to standardize the layout and to
159enable special debugging fields in debug builds. Note that there is
160no semicolon after the <code>PyObject_HEAD</code> macro; one is included in
161the macro definition. Be wary of adding one by accident; it's easy to
162do from habit, and your compiler might not complain, but someone
163else's probably will! (On Windows, MSVC is known to call this an
164error and refuse to compile the code.)
165
166<P>
167For contrast, let's take a look at the corresponding definition for
168standard Python integers:
169
170<P>
171<div class="verbatim"><pre>
172typedef struct {
173 PyObject_HEAD
174 long ob_ival;
175} PyIntObject;
176</pre></div>
177
178<P>
179Moving on, we come to the crunch -- the type object.
180
181<P>
182<div class="verbatim"><pre>
183static PyTypeObject noddy_NoddyType = {
184 PyObject_HEAD_INIT(NULL)
185 0, /*ob_size*/
186 "noddy.Noddy", /*tp_name*/
187 sizeof(noddy_NoddyObject), /*tp_basicsize*/
188 0, /*tp_itemsize*/
189 0, /*tp_dealloc*/
190 0, /*tp_print*/
191 0, /*tp_getattr*/
192 0, /*tp_setattr*/
193 0, /*tp_compare*/
194 0, /*tp_repr*/
195 0, /*tp_as_number*/
196 0, /*tp_as_sequence*/
197 0, /*tp_as_mapping*/
198 0, /*tp_hash */
199 0, /*tp_call*/
200 0, /*tp_str*/
201 0, /*tp_getattro*/
202 0, /*tp_setattro*/
203 0, /*tp_as_buffer*/
204 Py_TPFLAGS_DEFAULT, /*tp_flags*/
205 "Noddy objects", /* tp_doc */
206};
207</pre></div>
208
209<P>
210Now if you go and look up the definition of <tt class="ctype">PyTypeObject</tt> in
211<span class="file">object.h</span> you'll see that it has many more fields that the
212definition above. The remaining fields will be filled with zeros by
213the C compiler, and it's common practice to not specify them
214explicitly unless you need them.
215
216<P>
217This is so important that we're going to pick the top of it apart still
218further:
219
220<P>
221<div class="verbatim"><pre>
222 PyObject_HEAD_INIT(NULL)
223</pre></div>
224
225<P>
226This line is a bit of a wart; what we'd like to write is:
227
228<P>
229<div class="verbatim"><pre>
230 PyObject_HEAD_INIT(&amp;PyType_Type)
231</pre></div>
232
233<P>
234as the type of a type object is ``type'', but this isn't strictly
235conforming C and some compilers complain. Fortunately, this member
236will be filled in for us by <tt class="cfunction">PyType_Ready()</tt>.
237
238<P>
239<div class="verbatim"><pre>
240 0, /* ob_size */
241</pre></div>
242
243<P>
244The <tt class="member">ob_size</tt> field of the header is not used; its presence in
245the type structure is a historical artifact that is maintained for
246binary compatibility with extension modules compiled for older
247versions of Python. Always set this field to zero.
248
249<P>
250<div class="verbatim"><pre>
251 "noddy.Noddy", /* tp_name */
252</pre></div>
253
254<P>
255The name of our type. This will appear in the default textual
256representation of our objects and in some error messages, for example:
257
258<P>
259<div class="verbatim"><pre>
260&gt;&gt;&gt; "" + noddy.new_noddy()
261Traceback (most recent call last):
262 File "&lt;stdin&gt;", line 1, in ?
263TypeError: cannot add type "noddy.Noddy" to string
264</pre></div>
265
266<P>
267Note that the name is a dotted name that includes both the module name
268and the name of the type within the module. The module in this case is
269<tt class="module">noddy</tt> and the type is <tt class="class">Noddy</tt>, so we set the type name
270to <tt class="class">noddy.Noddy</tt>.
271
272<P>
273<div class="verbatim"><pre>
274 sizeof(noddy_NoddyObject), /* tp_basicsize */
275</pre></div>
276
277<P>
278This is so that Python knows how much memory to allocate when you call
279<tt class="cfunction">PyObject_New()</tt>.
280
281<P>
282<span class="note"><b class="label">Note:</b>
283If you want your type to be subclassable from Python, and your
284type has the same <tt class="member">tp_basicsize</tt> as its base type, you may
285have problems with multiple inheritance. A Python subclass of your
286type will have to list your type first in its <tt class="member">__bases__</tt>, or
287else it will not be able to call your type's <tt class="method">__new__</tt> method
288without getting an error. You can avoid this problem by ensuring
289that your type has a larger value for <tt class="member">tp_basicsize</tt> than
290its base type does. Most of the time, this will be true anyway,
291because either your base type will be <tt class="class">object</tt>, or else you will
292be adding data members to your base type, and therefore increasing its
293size.</span>
294
295<P>
296<div class="verbatim"><pre>
297 0, /* tp_itemsize */
298</pre></div>
299
300<P>
301This has to do with variable length objects like lists and strings.
302Ignore this for now.
303
304<P>
305Skipping a number of type methods that we don't provide, we set the
306class flags to <tt class="constant">Py_TPFLAGS_DEFAULT</tt>.
307
308<P>
309<div class="verbatim"><pre>
310 Py_TPFLAGS_DEFAULT, /*tp_flags*/
311</pre></div>
312
313<P>
314All types should include this constant in their flags. It enables all
315of the members defined by the current version of Python.
316
317<P>
318We provide a doc string for the type in <tt class="member">tp_doc</tt>.
319
320<P>
321<div class="verbatim"><pre>
322 "Noddy objects", /* tp_doc */
323</pre></div>
324
325<P>
326Now we get into the type methods, the things that make your objects
327different from the others. We aren't going to implement any of these
328in this version of the module. We'll expand this example later to
329have more interesting behavior.
330
331<P>
332For now, all we want to be able to do is to create new <tt class="class">Noddy</tt>
333objects. To enable object creation, we have to provide a
334<tt class="member">tp_new</tt> implementation. In this case, we can just use the
335default implementation provided by the API function
336<tt class="cfunction">PyType_GenericNew()</tt>. We'd like to just assign this to the
337<tt class="member">tp_new</tt> slot, but we can't, for portability sake, On some
338platforms or compilers, we can't statically initialize a structure
339member with a function defined in another C module, so, instead, we'll
340assign the <tt class="member">tp_new</tt> slot in the module initialization function
341just before calling <tt class="cfunction">PyType_Ready()</tt>:
342
343<P>
344<div class="verbatim"><pre>
345 noddy_NoddyType.tp_new = PyType_GenericNew;
346 if (PyType_Ready(&amp;noddy_NoddyType) &lt; 0)
347 return;
348</pre></div>
349
350<P>
351All the other type methods are <tt class="constant">NULL</tt>, so we'll go over them later
352-- that's for a later section!
353
354<P>
355Everything else in the file should be familiar, except for some code
356in <tt class="cfunction">initnoddy()</tt>:
357
358<P>
359<div class="verbatim"><pre>
360 if (PyType_Ready(&amp;noddy_NoddyType) &lt; 0)
361 return;
362</pre></div>
363
364<P>
365This initializes the <tt class="class">Noddy</tt> type, filing in a number of
366members, including <tt class="member">ob_type</tt> that we initially set to <tt class="constant">NULL</tt>.
367
368<P>
369<div class="verbatim"><pre>
370 PyModule_AddObject(m, "Noddy", (PyObject *)&amp;noddy_NoddyType);
371</pre></div>
372
373<P>
374This adds the type to the module dictionary. This allows us to create
375<tt class="class">Noddy</tt> instances by calling the <tt class="class">Noddy</tt> class:
376
377<P>
378<div class="verbatim"><pre>
379&gt;&gt;&gt; import noddy
380&gt;&gt;&gt; mynoddy = noddy.Noddy()
381</pre></div>
382
383<P>
384That's it! All that remains is to build it; put the above code in a
385file called <span class="file">noddy.c</span> and
386
387<P>
388<div class="verbatim"><pre>
389from distutils.core import setup, Extension
390setup(name="noddy", version="1.0",
391 ext_modules=[Extension("noddy", ["noddy.c"])])
392</pre></div>
393
394<P>
395in a file called <span class="file">setup.py</span>; then typing
396
397<P>
398<div class="verbatim"><pre>
399$ python setup.py build
400</pre></div>
401<P>
402at a shell should produce a file <span class="file">noddy.so</span> in a subdirectory;
403move to that directory and fire up Python -- you should be able to
404<code>import noddy</code> and play around with Noddy objects.
405
406<P>
407That wasn't so hard, was it?
408
409<P>
410Of course, the current Noddy type is pretty uninteresting. It has no
411data and doesn't do anything. It can't even be subclassed.
412
413<P>
414
415<p><br /></p><hr class='online-navigation' />
416<div class='online-navigation'>
417<!--Table of Child-Links-->
418<A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a>
419
420<UL CLASS="ChildLinks">
421<LI><A href="node22.html">2.1.1 Adding data and methods to the Basic example</a>
422<LI><A href="node23.html">2.1.2 Providing finer control over data attributes</a>
423<LI><A href="node24.html">2.1.3 Supporting cyclic garbage collection</a>
424</ul>
425<!--End of Table of Child-Links-->
426</div>
427
428<DIV CLASS="navigation">
429<div class='online-navigation'>
430<p></p><hr />
431<table align="center" width="100%" cellpadding="0" cellspacing="2">
432<tr>
433<td class='online-navigation'><a rel="prev" title="2. Defining New Types"
434 href="defining-new-types.html"><img src='../icons/previous.png'
435 border='0' height='32' alt='Previous Page' width='32' /></A></td>
436<td class='online-navigation'><a rel="parent" title="2. Defining New Types"
437 href="defining-new-types.html"><img src='../icons/up.png'
438 border='0' height='32' alt='Up One Level' width='32' /></A></td>
439<td class='online-navigation'><a rel="next" title="2.1.1 Adding data and"
440 href="node22.html"><img src='../icons/next.png'
441 border='0' height='32' alt='Next Page' width='32' /></A></td>
442<td align="center" width="100%">Extending and Embedding the Python Interpreter</td>
443<td class='online-navigation'><a rel="contents" title="Table of Contents"
444 href="contents.html"><img src='../icons/contents.png'
445 border='0' height='32' alt='Contents' width='32' /></A></td>
446<td class='online-navigation'><img src='../icons/blank.png'
447 border='0' height='32' alt='' width='32' /></td>
448<td class='online-navigation'><img src='../icons/blank.png'
449 border='0' height='32' alt='' width='32' /></td>
450</tr></table>
451<div class='online-navigation'>
452<b class="navlabel">Previous:</b>
453<a class="sectref" rel="prev" href="defining-new-types.html">2. Defining New Types</A>
454<b class="navlabel">Up:</b>
455<a class="sectref" rel="parent" href="defining-new-types.html">2. Defining New Types</A>
456<b class="navlabel">Next:</b>
457<a class="sectref" rel="next" href="node22.html">2.1.1 Adding data and</A>
458</div>
459</div>
460<hr />
461<span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span>
462</DIV>
463<!--End of Navigation Panel-->
464<ADDRESS>
465See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
466</ADDRESS>
467</BODY>
468</HTML>