Merged pull request #12 from bhy/T423.
[cython.git] / docs / src / userguide / sharing_declarations.rst
1 .. highlight:: cython
2
3 .. _sharing-declarations:
4
5 ********************************************
6 Sharing Declarations Between Cython Modules
7 ********************************************
8
9 This section describes a new set of facilities for making C declarations,
10 functions and extension types in one Cython module available for use in
11 another Cython module. These facilities are closely modelled on the Python
12 import mechanism, and can be thought of as a compile-time version of it.
13
14 Definition and Implementation files
15 ====================================
16
17 A Cython module can be split into two parts: a definition file with a ``.pxd``
18 suffix, containing C declarations that are to be available to other Cython
19 modules, and an implementation file with a ``.pyx`` suffix, containing
20 everything else. When a module wants to use something declared in another
21 module's definition file, it imports it using the :keyword:`cimport`
22 statement.
23
24 A ``.pxd`` file that consists solely of extern declarations does not need
25 to correspond to an actual ``.pyx`` file or Python module. This can make it a
26 convenient place to put common declarations, for example declarations of 
27 functions from  an :ref:`external library <external-C-code>` that one wants to use in several modules. 
28
29 What a Definition File contains
30 ================================
31
32 A definition file can contain:
33
34 * Any kind of C type declaration.
35 * extern C function or variable declarations.
36 * Declarations of C functions defined in the module.
37 * The definition part of an extension type (see below).
38
39 It cannot contain any non-extern C variable declarations.
40
41 It cannot contain the implementations of any C or Python functions, or any
42 Python class definitions, or any executable statements. It is needed when one 
43 wants to  access :keyword:`cdef` attributes and methods, or to inherit from 
44 :keyword:`cdef` classes defined in this module. 
45
46 .. note::
47
48     You don't need to (and shouldn't) declare anything in a declaration file
49     public in order to make it available to other Cython modules; its mere
50     presence in a definition file does that. You only need a public
51     declaration if you want to make something available to external C code.
52
53 What an Implementation File contains
54 ======================================
55
56 An implementation file can contain any kind of Cython statement, although there
57 are some restrictions on the implementation part of an extension type if the
58 corresponding definition file also defines that type (see below). 
59 If one doesn't need to :keyword:`cimport` anything from this module, then this
60 is the only file one needs. 
61
62 The cimport statement
63 =======================
64
65 The :keyword:`cimport` statement is used in a definition or
66 implementation file to gain access to names declared in another definition
67 file. Its syntax exactly parallels that of the normal Python import
68 statement::
69
70     cimport module [, module...]
71
72     from module cimport name [as name] [, name [as name] ...]
73
74 Here is an example. The file on the left is a definition file which exports a
75 C data type. The file on the right is an implementation file which imports and
76 uses it.
77  
78 :file:`dishes.pxd`::
79
80    cdef enum otherstuff:       
81        sausage, eggs, lettuce  
82                                
83    cdef struct spamdish:       
84        int oz_of_spam          
85        otherstuff filler       
86                                
87 :file:`restaurant.pyx`::
88
89     cimport dishes
90     from dishes cimport spamdish
91
92     cdef void prepare(spamdish *d):
93         d.oz_of_spam = 42
94         d.filler = dishes.sausage
95
96     def serve():
97         cdef spamdish d
98         prepare(&d)
99         print "%d oz spam, filler no. %d" % (d.oz_of_spam, d.otherstuff)
100                                
101 It is important to understand that the :keyword:`cimport` statement can only
102 be used to import C data types, C functions and variables, and extension
103 types. It cannot be used to import any Python objects, and (with one
104 exception) it doesn't imply any Python import at run time. If you want to
105 refer to any Python names from a module that you have cimported, you will have
106 to include a regular import statement for it as well.
107
108 The exception is that when you use :keyword:`cimport` to import an extension type, its
109 type object is imported at run time and made available by the name under which
110 you imported it. Using :keyword:`cimport` to import extension types is covered in more
111 detail below.  
112
113 If a ``.pxd`` file changes, any modules that :keyword:`cimport` from it may need to be 
114 recompiled. 
115
116 Search paths for definition files 
117 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
118
119 When you :keyword:`cimport` a module called ``modulename``, the Cython
120 compiler searches for a file called :file:`modulename.pxd` along the search
121 path for include files, as specified by ``-I`` command line options.
122
123 Also, whenever you compile a file :file:`modulename.pyx`, the corresponding
124 definition file :file:`modulename.pxd` is first searched for along the same
125 path, and if found, it is processed before processing the ``.pyx`` file.  
126
127 Using cimport to resolve naming conflicts 
128 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
129
130 The :keyword:`cimport` mechanism provides a clean and simple way to solve the
131 problem of wrapping external C functions with Python functions of the same
132 name. All you need to do is put the extern C declarations into a ``.pxd`` file
133 for an imaginary module, and :keyword:`cimport` that module. You can then
134 refer to the C functions by qualifying them with the name of the module.
135 Here's an example:
136  
137 :file:`c_lunch.pxd` ::
138
139     cdef extern from "lunch.h":
140         void eject_tomato(float)        
141
142 :file:`lunch.pyx` ::
143
144     cimport c_lunch
145
146     def eject_tomato(float speed):
147         c_lunch.eject_tomato(speed)
148
149 You don't need any :file:`c_lunch.pyx` file, because the only things defined
150 in :file:`c_lunch.pxd` are extern C entities. There won't be any actual
151 ``c_lunch`` module at run time, but that doesn't matter; the
152 :file:`c_lunch.pxd` file has done its job of providing an additional namespace
153 at compile time.  
154
155 Sharing C Functions
156 ===================
157
158 C functions defined at the top level of a module can be made available via
159 :keyword:`cimport` by putting headers for them in the ``.pxd`` file, for
160 example,:
161
162 :file:`volume.pxd`::
163
164     cdef float cube(float)
165
166 :file:`spammery.pyx`::
167
168     from volume cimport cube
169
170     def menu(description, size):
171         print description, ":", cube(size), \
172             "cubic metres of spam"
173
174     menu("Entree", 1)
175     menu("Main course", 3)
176     menu("Dessert", 2)
177
178 :file:`volume.pyx`::
179
180     cdef float cube(float x):
181         return x * x * x
182
183 .. note::
184
185     When a module exports a C function in this way, an object appears in the
186     module dictionary under the function's name. However, you can't make use of
187     this object from Python, nor can you use it from Cython using a normal import
188     statement; you have to use :keyword:`cimport`.  
189
190 Sharing Extension Types 
191 =======================
192
193 An extension type can be made available via :keyword:`cimport` by splitting
194 its definition into two parts, one in a definition file and the other in the
195 corresponding implementation file.
196
197 The definition part of the extension type can only declare C attributes and C
198 methods, not Python methods, and it must declare all of that type's C
199 attributes and C methods.
200
201 The implementation part must implement all of the C methods declared in the
202 definition part, and may not add any further C attributes. It may also define
203 Python methods.
204
205 Here is an example of a module which defines and exports an extension type,
206 and another module which uses it.::
207  
208     # Shrubbing.pxd
209     cdef class Shrubbery:
210         cdef int width
211         cdef int length
212         
213     # Shrubbing.pyx
214     cdef class Shrubbery:
215         def __cinit__(self, int w, int l):
216             self.width = w
217             self.length = l
218
219     def standard_shrubbery():
220         return Shrubbery(3, 7)
221
222
223     # Landscaping.pyx
224     cimport Shrubbing
225     import Shrubbing
226
227     cdef Shrubbing.Shrubbery sh
228     sh = Shrubbing.standard_shrubbery()
229     print "Shrubbery size is %d x %d" % (sh.width, sh.height)
230  
231 Some things to note about this example:
232
233 * There is a :keyword:`cdef` class Shrubbery declaration in both
234   :file:`Shrubbing.pxd` and :file:`Shrubbing.pyx`. When the Shrubbing module
235   is compiled, these two declarations are combined into one.
236 * In Landscaping.pyx, the :keyword:`cimport` Shrubbing declaration allows us
237   to refer to the Shrubbery type as :class:`Shrubbing.Shrubbery`. But it
238   doesn't bind the name Shrubbing in Landscaping's module namespace at run
239   time, so to access :func:`Shrubbing.standard_shrubbery` we also need to
240   ``import Shrubbing``.
241