blob: 1f96e824508828d6549c37fef61665549e706ac2 [file] [log] [blame]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001======================
2Argument Clinic How-To
3======================
4
5:author: Larry Hastings
6
7
8.. topic:: Abstract
9
10 Argument Clinic is a preprocessor for CPython C files.
11 Its purpose is to automate all the boilerplate involved
12 with writing argument parsing code for "builtins".
13 This document shows you how to convert your first C
14 function to work with Argument Clinic, and then introduces
15 some advanced topics on Argument Clinic usage.
16
Larry Hastings6d2ea212014-01-05 02:50:45 -080017 Currently Argument Clinic is considered internal-only
18 for CPython. Its use is not supported for files outside
19 CPython, and no guarantees are made regarding backwards
20 compatibility for future versions. In other words: if you
21 maintain an external C extension for CPython, you're welcome
22 to experiment with Argument Clinic in your own code. But the
23 version of Argument Clinic that ships with CPython 3.5 *could*
24 be totally incompatible and break all your code.
Larry Hastings78cf85c2014-01-04 12:44:57 -080025
Larry Hastingsbebf7352014-01-17 17:47:17 -080026============================
27The Goals Of Argument Clinic
28============================
29
30Argument Clinic's primary goal
31is to take over responsibility for all argument parsing code
32inside CPython. This means that, when you convert a function
33to work with Argument Clinic, that function should no longer
34do any of its own argument parsing--the code generated by
35Argument Clinic should be a "black box" to you, where CPython
36calls in at the top, and your code gets called at the bottom,
37with ``PyObject *args`` (and maybe ``PyObject *kwargs``)
38magically converted into the C variables and types you need.
39
40In order for Argument Clinic to accomplish its primary goal,
41it must be easy to use. Currently, working with CPython's
42argument parsing library is a chore, requiring maintaining
43redundant information in a surprising number of places.
44When you use Argument Clinic, you don't have to repeat yourself.
45
46Obviously, no one would want to use Argument Clinic unless
Larry Hastings537d7602014-01-18 01:08:50 -080047it's solving their problem--and without creating new problems of
Larry Hastingsbebf7352014-01-17 17:47:17 -080048its own.
Larry Hastings537d7602014-01-18 01:08:50 -080049So it's paramount that Argument Clinic generate correct code.
50It'd be nice if the code was faster, too, but at the very least
51it should not introduce a major speed regression. (Eventually Argument
52Clinic *should* make a major speedup possible--we could
53rewrite its code generator to produce tailor-made argument
54parsing code, rather than calling the general-purpose CPython
55argument parsing library. That would make for the fastest
56argument parsing possible!)
Larry Hastingsbebf7352014-01-17 17:47:17 -080057
58Additionally, Argument Clinic must be flexible enough to
59work with any approach to argument parsing. Python has
60some functions with some very strange parsing behaviors;
61Argument Clinic's goal is to support all of them.
62
63Finally, the original motivation for Argument Clinic was
64to provide introspection "signatures" for CPython builtins.
65It used to be, the introspection query functions would throw
66an exception if you passed in a builtin. With Argument
67Clinic, that's a thing of the past!
68
69One idea you should keep in mind, as you work with
70Argument Clinic: the more information you give it, the
71better job it'll be able to do.
72Argument Clinic is admittedly relatively simple right
73now. But as it evolves it will get more sophisticated,
74and it should be able to do many interesting and smart
75things with all the information you give it.
76
77
Larry Hastings78cf85c2014-01-04 12:44:57 -080078========================
79Basic Concepts And Usage
80========================
81
Larry Hastings6d2ea212014-01-05 02:50:45 -080082Argument Clinic ships with CPython; you'll find it in ``Tools/clinic/clinic.py``.
Larry Hastings78cf85c2014-01-04 12:44:57 -080083If you run that script, specifying a C file as an argument::
84
85 % python3 Tools/clinic/clinic.py foo.c
86
87Argument Clinic will scan over the file looking for lines that
88look exactly like this::
89
Larry Hastings61272b72014-01-07 12:41:53 -080090 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -080091
92When it finds one, it reads everything up to a line that looks
Larry Hastings61272b72014-01-07 12:41:53 -080093exactly like this::
Larry Hastings78cf85c2014-01-04 12:44:57 -080094
Larry Hastings61272b72014-01-07 12:41:53 -080095 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -080096
97Everything in between these two lines is input for Argument Clinic.
98All of these lines, including the beginning and ending comment
Larry Hastings6d2ea212014-01-05 02:50:45 -080099lines, are collectively called an Argument Clinic "block".
Larry Hastings78cf85c2014-01-04 12:44:57 -0800100
101When Argument Clinic parses one of these blocks, it
102generates output. This output is rewritten into the C file
103immediately after the block, followed by a comment containing a checksum.
Larry Hastings6d2ea212014-01-05 02:50:45 -0800104The Argument Clinic block now looks like this::
Larry Hastings78cf85c2014-01-04 12:44:57 -0800105
Larry Hastings61272b72014-01-07 12:41:53 -0800106 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800107 ... clinic input goes here ...
Larry Hastings61272b72014-01-07 12:41:53 -0800108 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800109 ... clinic output goes here ...
Larry Hastings61272b72014-01-07 12:41:53 -0800110 /*[clinic end generated code: checksum=...]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800111
112If you run Argument Clinic on the same file a second time, Argument Clinic
113will discard the old output and write out the new output with a fresh checksum
114line. However, if the input hasn't changed, the output won't change either.
115
116You should never modify the output portion of an Argument Clinic block. Instead,
117change the input until it produces the output you want. (That's the purpose of the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800118checksum--to detect if someone changed the output, as these edits would be lost
119the next time Argument Clinic writes out fresh output.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800120
121For the sake of clarity, here's the terminology we'll use with Argument Clinic:
122
Larry Hastings61272b72014-01-07 12:41:53 -0800123* The first line of the comment (``/*[clinic input]``) is the *start line*.
124* The last line of the initial comment (``[clinic start generated code]*/``) is the *end line*.
125* The last line (``/*[clinic end generated code: checksum=...]*/``) is the *checksum line*.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800126* In between the start line and the end line is the *input*.
127* In between the end line and the checksum line is the *output*.
128* All the text collectively, from the start line to the checksum line inclusively,
129 is the *block*. (A block that hasn't been successfully processed by Argument
130 Clinic yet doesn't have output or a checksum line, but it's still considered
131 a block.)
132
133
134==============================
135Converting Your First Function
136==============================
137
138The best way to get a sense of how Argument Clinic works is to
Larry Hastingsbebf7352014-01-17 17:47:17 -0800139convert a function to work with it. Here, then, are the bare
140minimum steps you'd need to follow to convert a function to
141work with Argument Clinic. Note that for code you plan to
142check in to CPython, you really should take the conversion farther,
143using some of the advanced concepts you'll see later on in
144the document (like "return converters" and "self converters").
145But we'll keep it simple for this walkthrough so you can learn.
146
147Let's dive in!
Larry Hastings78cf85c2014-01-04 12:44:57 -0800148
Larry Hastings6d2ea212014-01-05 02:50:45 -08001490. Make sure you're working with a freshly updated checkout
150 of the CPython trunk.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800151
Larry Hastings6d2ea212014-01-05 02:50:45 -08001521. Find a Python builtin that calls either :c:func:`PyArg_ParseTuple`
153 or :c:func:`PyArg_ParseTupleAndKeywords`, and hasn't been converted
154 to work with Argument Clinic yet.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800155 For my example I'm using ``pickle.Pickler.dump()``.
156
1572. If the call to the ``PyArg_Parse`` function uses any of the
158 following format units::
159
160 O&
161 O!
162 es
163 es#
164 et
165 et#
166
Larry Hastings6d2ea212014-01-05 02:50:45 -0800167 or if it has multiple calls to :c:func:`PyArg_ParseTuple`,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800168 you should choose a different function. Argument Clinic *does*
169 support all of these scenarios. But these are advanced
170 topics--let's do something simpler for your first function.
171
Larry Hastings4a55fc52014-01-12 11:09:57 -0800172 Also, if the function has multiple calls to :c:func:`PyArg_ParseTuple`
173 or :c:func:`PyArg_ParseTupleAndKeywords` where it supports different
174 types for the same argument, or if the function uses something besides
175 PyArg_Parse functions to parse its arguments, it probably
176 isn't suitable for conversion to Argument Clinic. Argument Clinic
177 doesn't support generic functions or polymorphic parameters.
178
Larry Hastings78cf85c2014-01-04 12:44:57 -08001793. Add the following boilerplate above the function, creating our block::
180
Larry Hastings61272b72014-01-07 12:41:53 -0800181 /*[clinic input]
182 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800183
1844. Cut the docstring and paste it in between the ``[clinic]`` lines,
185 removing all the junk that makes it a properly quoted C string.
186 When you're done you should have just the text, based at the left
187 margin, with no line wider than 80 characters.
188 (Argument Clinic will preserve indents inside the docstring.)
189
Larry Hastings2a727912014-01-16 11:32:01 -0800190 If the old docstring had a first line that looked like a function
191 signature, throw that line away. (The docstring doesn't need it
192 anymore--when you use ``help()`` on your builtin in the future,
193 the first line will be built automatically based on the function's
194 signature.)
195
Larry Hastings78cf85c2014-01-04 12:44:57 -0800196 Sample::
197
Larry Hastings61272b72014-01-07 12:41:53 -0800198 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800199 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800200 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800201
2025. If your docstring doesn't have a "summary" line, Argument Clinic will
203 complain. So let's make sure it has one. The "summary" line should
204 be a paragraph consisting of a single 80-column line
205 at the beginning of the docstring.
206
Larry Hastings6d2ea212014-01-05 02:50:45 -0800207 (Our example docstring consists solely of a summary line, so the sample
Larry Hastings78cf85c2014-01-04 12:44:57 -0800208 code doesn't have to change for this step.)
209
2106. Above the docstring, enter the name of the function, followed
211 by a blank line. This should be the Python name of the function,
212 and should be the full dotted path
213 to the function--it should start with the name of the module,
214 include any sub-modules, and if the function is a method on
215 a class it should include the class name too.
216
217 Sample::
218
Larry Hastings61272b72014-01-07 12:41:53 -0800219 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800220 pickle.Pickler.dump
221
222 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800223 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800224
2257. If this is the first time that module or class has been used with Argument
226 Clinic in this C file,
227 you must declare the module and/or class. Proper Argument Clinic hygiene
228 prefers declaring these in a separate block somewhere near the
229 top of the C file, in the same way that include files and statics go at
230 the top. (In our sample code we'll just show the two blocks next to
231 each other.)
232
233 Sample::
234
Larry Hastings61272b72014-01-07 12:41:53 -0800235 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800236 module pickle
237 class pickle.Pickler
Larry Hastings61272b72014-01-07 12:41:53 -0800238 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800239
Larry Hastings61272b72014-01-07 12:41:53 -0800240 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800241 pickle.Pickler.dump
242
243 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800244 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800245
Larry Hastings4a55fc52014-01-12 11:09:57 -0800246 The name of the class and module should be the same as the one
247 seen by Python. Check the name defined in the :c:type:`PyModuleDef`
248 or :c:type:`PyTypeObject` as appropriate.
249
250
Larry Hastings78cf85c2014-01-04 12:44:57 -0800251
2528. Declare each of the parameters to the function. Each parameter
253 should get its own line. All the parameter lines should be
254 indented from the function name and the docstring.
255
256 The general form of these parameter lines is as follows::
257
258 name_of_parameter: converter
259
260 If the parameter has a default value, add that after the
261 converter::
262
263 name_of_parameter: converter = default_value
264
Larry Hastings2a727912014-01-16 11:32:01 -0800265 Argument Clinic's support for "default values" is quite sophisticated;
266 please see :ref:`the section below on default values <default_values>`
267 for more information.
268
Larry Hastings78cf85c2014-01-04 12:44:57 -0800269 Add a blank line below the parameters.
270
271 What's a "converter"? It establishes both the type
272 of the variable used in C, and the method to convert the Python
273 value into a C value at runtime.
274 For now you're going to use what's called a "legacy converter"--a
275 convenience syntax intended to make porting old code into Argument
276 Clinic easier.
277
278 For each parameter, copy the "format unit" for that
279 parameter from the ``PyArg_Parse()`` format argument and
280 specify *that* as its converter, as a quoted
281 string. ("format unit" is the formal name for the one-to-three
282 character substring of the ``format`` parameter that tells
283 the argument parsing function what the type of the variable
Larry Hastings6d2ea212014-01-05 02:50:45 -0800284 is and how to convert it. For more on format units please
285 see :ref:`arg-parsing`.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800286
287 For multicharacter format units like ``z#``, use the
288 entire two-or-three character string.
289
290 Sample::
291
Larry Hastings61272b72014-01-07 12:41:53 -0800292 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800293 module pickle
294 class pickle.Pickler
Larry Hastings61272b72014-01-07 12:41:53 -0800295 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800296
Larry Hastings61272b72014-01-07 12:41:53 -0800297 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800298 pickle.Pickler.dump
299
300 obj: 'O'
301
302 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800303 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800304
3059. If your function has ``|`` in the format string, meaning some
306 parameters have default values, you can ignore it. Argument
307 Clinic infers which parameters are optional based on whether
308 or not they have default values.
309
310 If your function has ``$`` in the format string, meaning it
311 takes keyword-only arguments, specify ``*`` on a line by
312 itself before the first keyword-only argument, indented the
313 same as the parameter lines.
314
315 (``pickle.Pickler.dump`` has neither, so our sample is unchanged.)
316
317
Larry Hastings6d2ea212014-01-05 02:50:45 -080031810. If the existing C function calls :c:func:`PyArg_ParseTuple`
319 (as opposed to :c:func:`PyArg_ParseTupleAndKeywords`), then all its
Larry Hastings78cf85c2014-01-04 12:44:57 -0800320 arguments are positional-only.
321
322 To mark all parameters as positional-only in Argument Clinic,
323 add a ``/`` on a line by itself after the last parameter,
324 indented the same as the parameter lines.
325
Larry Hastings6d2ea212014-01-05 02:50:45 -0800326 Currently this is all-or-nothing; either all parameters are
327 positional-only, or none of them are. (In the future Argument
328 Clinic may relax this restriction.)
329
Larry Hastings78cf85c2014-01-04 12:44:57 -0800330 Sample::
331
Larry Hastings61272b72014-01-07 12:41:53 -0800332 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800333 module pickle
334 class pickle.Pickler
Larry Hastings61272b72014-01-07 12:41:53 -0800335 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800336
Larry Hastings61272b72014-01-07 12:41:53 -0800337 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800338 pickle.Pickler.dump
339
340 obj: 'O'
341 /
342
343 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800344 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800345
Larry Hastings6d2ea212014-01-05 02:50:45 -080034611. It's helpful to write a per-parameter docstring for each parameter.
347 But per-parameter docstrings are optional; you can skip this step
348 if you prefer.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800349
Larry Hastings6d2ea212014-01-05 02:50:45 -0800350 Here's how to add a per-parameter docstring. The first line
Larry Hastings78cf85c2014-01-04 12:44:57 -0800351 of the per-parameter docstring must be indented further than the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800352 parameter definition. The left margin of this first line establishes
353 the left margin for the whole per-parameter docstring; all the text
354 you write will be outdented by this amount. You can write as much
355 text as you like, across multiple lines if you wish.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800356
357 Sample::
358
Larry Hastings61272b72014-01-07 12:41:53 -0800359 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800360 module pickle
361 class pickle.Pickler
Larry Hastings61272b72014-01-07 12:41:53 -0800362 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800363
Larry Hastings61272b72014-01-07 12:41:53 -0800364 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800365 pickle.Pickler.dump
366
367 obj: 'O'
368 The object to be pickled.
369 /
370
371 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800372 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800373
37412. Save and close the file, then run ``Tools/clinic/clinic.py`` on it.
375 With luck everything worked and your block now has output! Reopen
376 the file in your text editor to see::
377
Larry Hastings61272b72014-01-07 12:41:53 -0800378 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800379 module pickle
380 class pickle.Pickler
Larry Hastings61272b72014-01-07 12:41:53 -0800381 [clinic start generated code]*/
382 /*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800383
Larry Hastings61272b72014-01-07 12:41:53 -0800384 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800385 pickle.Pickler.dump
386
387 obj: 'O'
388 The object to be pickled.
389 /
390
391 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800392 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800393
394 PyDoc_STRVAR(pickle_Pickler_dump__doc__,
395 "Write a pickled representation of obj to the open file.\n"
396 "\n"
397 ...
398 static PyObject *
399 pickle_Pickler_dump_impl(PyObject *self, PyObject *obj)
Larry Hastings61272b72014-01-07 12:41:53 -0800400 /*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800401
Larry Hastings6d2ea212014-01-05 02:50:45 -0800402 Obviously, if Argument Clinic didn't produce any output, it's because
403 it found an error in your input. Keep fixing your errors and retrying
404 until Argument Clinic processes your file without complaint.
405
Larry Hastings78cf85c2014-01-04 12:44:57 -080040613. Double-check that the argument-parsing code Argument Clinic generated
407 looks basically the same as the existing code.
408
409 First, ensure both places use the same argument-parsing function.
410 The existing code must call either
Larry Hastings6d2ea212014-01-05 02:50:45 -0800411 :c:func:`PyArg_ParseTuple` or :c:func:`PyArg_ParseTupleAndKeywords`;
Larry Hastings78cf85c2014-01-04 12:44:57 -0800412 ensure that the code generated by Argument Clinic calls the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800413 *exact* same function.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800414
Larry Hastings6d2ea212014-01-05 02:50:45 -0800415 Second, the format string passed in to :c:func:`PyArg_ParseTuple` or
416 :c:func:`PyArg_ParseTupleAndKeywords` should be *exactly* the same
417 as the hand-written one in the existing function, up to the colon
418 or semi-colon.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800419
Larry Hastings6d2ea212014-01-05 02:50:45 -0800420 (Argument Clinic always generates its format strings
421 with a ``:`` followed by the name of the function. If the
422 existing code's format string ends with ``;``, to provide
423 usage help, this change is harmless--don't worry about it.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800424
Larry Hastings6d2ea212014-01-05 02:50:45 -0800425 Third, for parameters whose format units require two arguments
426 (like a length variable, or an encoding string, or a pointer
427 to a conversion function), ensure that the second argument is
428 *exactly* the same between the two invocations.
429
430 Fourth, inside the output portion of the block you'll find a preprocessor
431 macro defining the appropriate static :c:type:`PyMethodDef` structure for
432 this builtin::
433
434 #define _PICKLE_PICKLER_DUMP_METHODDEF \
435 {"dump", (PyCFunction)_pickle_Pickler_dump, METH_O, _pickle_Pickler_dump__doc__},
436
437 This static structure should be *exactly* the same as the existing static
438 :c:type:`PyMethodDef` structure for this builtin.
439
440 If any of these items differ in *any way*,
441 adjust your Argument Clinic function specification and rerun
442 ``Tools/clinic/clinic.py`` until they *are* the same.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800443
444
44514. Notice that the last line of its output is the declaration
446 of your "impl" function. This is where the builtin's implementation goes.
447 Delete the existing prototype of the function you're modifying, but leave
448 the opening curly brace. Now delete its argument parsing code and the
449 declarations of all the variables it dumps the arguments into.
450 Notice how the Python arguments are now arguments to this impl function;
451 if the implementation used different names for these variables, fix it.
Larry Hastings6d2ea212014-01-05 02:50:45 -0800452
453 Let's reiterate, just because it's kind of weird. Your code should now
454 look like this::
455
456 static return_type
457 your_function_impl(...)
Larry Hastings61272b72014-01-07 12:41:53 -0800458 /*[clinic end generated code: checksum=...]*/
Larry Hastings6d2ea212014-01-05 02:50:45 -0800459 {
460 ...
461
462 Argument Clinic generated the checksum line and the function prototype just
463 above it. You should write the opening (and closing) curly braces for the
464 function, and the implementation inside.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800465
466 Sample::
467
Larry Hastings61272b72014-01-07 12:41:53 -0800468 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800469 module pickle
470 class pickle.Pickler
Larry Hastings61272b72014-01-07 12:41:53 -0800471 [clinic start generated code]*/
472 /*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800473
Larry Hastings61272b72014-01-07 12:41:53 -0800474 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800475 pickle.Pickler.dump
476
477 obj: 'O'
478 The object to be pickled.
479 /
480
481 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800482 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800483
484 PyDoc_STRVAR(pickle_Pickler_dump__doc__,
485 "Write a pickled representation of obj to the open file.\n"
486 "\n"
487 ...
488 static PyObject *
489 pickle_Pickler_dump_impl(PyObject *self, PyObject *obj)
Larry Hastings61272b72014-01-07 12:41:53 -0800490 /*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800491 {
492 /* Check whether the Pickler was initialized correctly (issue3664).
493 Developers often forget to call __init__() in their subclasses, which
494 would trigger a segfault without this check. */
495 if (self->write == NULL) {
496 PyErr_Format(PicklingError,
497 "Pickler.__init__() was not called by %s.__init__()",
498 Py_TYPE(self)->tp_name);
499 return NULL;
500 }
501
502 if (_Pickler_ClearBuffer(self) < 0)
503 return NULL;
504
505 ...
506
Larry Hastings6d2ea212014-01-05 02:50:45 -080050715. Remember the macro with the :c:type:`PyMethodDef` structure for this
508 function? Find the existing :c:type:`PyMethodDef` structure for this
509 function and replace it with a reference to the macro. (If the builtin
510 is at module scope, this will probably be very near the end of the file;
511 if the builtin is a class method, this will probably be below but relatively
512 near to the implementation.)
513
514 Note that the body of the macro contains a trailing comma. So when you
515 replace the existing static :c:type:`PyMethodDef` structure with the macro,
516 *don't* add a comma to the end.
517
518 Sample::
519
520 static struct PyMethodDef Pickler_methods[] = {
521 _PICKLE_PICKLER_DUMP_METHODDEF
522 _PICKLE_PICKLER_CLEAR_MEMO_METHODDEF
523 {NULL, NULL} /* sentinel */
524 };
525
526
52716. Compile, then run the relevant portions of the regression-test suite.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800528 This change should not introduce any new compile-time warnings or errors,
529 and there should be no externally-visible change to Python's behavior.
530
531 Well, except for one difference: ``inspect.signature()`` run on your function
532 should now provide a valid signature!
533
534 Congratulations, you've ported your first function to work with Argument Clinic!
535
536===============
537Advanced Topics
538===============
539
Larry Hastings4a55fc52014-01-12 11:09:57 -0800540Now that you've had some experience working with Argument Clinic, it's time
541for some advanced topics.
542
543
544Symbolic default values
545-----------------------
546
547The default value you provide for a parameter can't be any arbitrary
548expression. Currently the following are explicitly supported:
549
550* Numeric constants (integer and float)
551* String constants
552* ``True``, ``False``, and ``None``
553* Simple symbolic constants like ``sys.maxsize``, which must
554 start with the name of the module
555
556In case you're curious, this is implemented in ``from_builtin()``
557in ``Lib/inspect.py``.
558
559(In the future, this may need to get even more elaborate,
560to allow full expressions like ``CONSTANT - 1``.)
561
Larry Hastings78cf85c2014-01-04 12:44:57 -0800562
563Renaming the C functions generated by Argument Clinic
564-----------------------------------------------------
565
566Argument Clinic automatically names the functions it generates for you.
567Occasionally this may cause a problem, if the generated name collides with
Larry Hastings6d2ea212014-01-05 02:50:45 -0800568the name of an existing C function. There's an easy solution: override the names
569used for the C functions. Just add the keyword ``"as"``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800570to your function declaration line, followed by the function name you wish to use.
Larry Hastings6d2ea212014-01-05 02:50:45 -0800571Argument Clinic will use that function name for the base (generated) function,
572then add ``"_impl"`` to the end and use that for the name of the impl function.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800573
574For example, if we wanted to rename the C function names generated for
575``pickle.Pickler.dump``, it'd look like this::
576
Larry Hastings61272b72014-01-07 12:41:53 -0800577 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800578 pickle.Pickler.dump as pickler_dumper
579
580 ...
581
582The base function would now be named ``pickler_dumper()``,
Larry Hastings6d2ea212014-01-05 02:50:45 -0800583and the impl function would now be named ``pickler_dumper_impl()``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800584
585
Larry Hastings4a55fc52014-01-12 11:09:57 -0800586
587Converting functions using PyArg_UnpackTuple
588--------------------------------------------
589
590To convert a function parsing its arguments with :c:func:`PyArg_UnpackTuple`,
591simply write out all the arguments, specifying each as an ``object``. You
592may specify the ``type`` argument to cast the type as appropriate. All
593arguments should be marked positional-only (add a ``/`` on a line by itself
594after the last argument).
595
596Currently the generated code will use :c:func:`PyArg_ParseTuple`, but this
597will change soon.
598
Larry Hastings78cf85c2014-01-04 12:44:57 -0800599Optional Groups
600---------------
601
602Some legacy functions have a tricky approach to parsing their arguments:
603they count the number of positional arguments, then use a ``switch`` statement
Larry Hastings6d2ea212014-01-05 02:50:45 -0800604to call one of several different :c:func:`PyArg_ParseTuple` calls depending on
Larry Hastings78cf85c2014-01-04 12:44:57 -0800605how many positional arguments there are. (These functions cannot accept
606keyword-only arguments.) This approach was used to simulate optional
Larry Hastings6d2ea212014-01-05 02:50:45 -0800607arguments back before :c:func:`PyArg_ParseTupleAndKeywords` was created.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800608
Larry Hastings6d2ea212014-01-05 02:50:45 -0800609While functions using this approach can often be converted to
610use :c:func:`PyArg_ParseTupleAndKeywords`, optional arguments, and default values,
611it's not always possible. Some of these legacy functions have
612behaviors :c:func:`PyArg_ParseTupleAndKeywords` doesn't directly support.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800613The most obvious example is the builtin function ``range()``, which has
614an optional argument on the *left* side of its required argument!
615Another example is ``curses.window.addch()``, which has a group of two
616arguments that must always be specified together. (The arguments are
617called ``x`` and ``y``; if you call the function passing in ``x``,
618you must also pass in ``y``--and if you don't pass in ``x`` you may not
619pass in ``y`` either.)
620
Larry Hastings6d2ea212014-01-05 02:50:45 -0800621In any case, the goal of Argument Clinic is to support argument parsing
622for all existing CPython builtins without changing their semantics.
623Therefore Argument Clinic supports
624this alternate approach to parsing, using what are called *optional groups*.
625Optional groups are groups of arguments that must all be passed in together.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800626They can be to the left or the right of the required arguments. They
627can *only* be used with positional-only parameters.
628
629To specify an optional group, add a ``[`` on a line by itself before
Larry Hastings6d2ea212014-01-05 02:50:45 -0800630the parameters you wish to group together, and a ``]`` on a line by itself
631after these parameters. As an example, here's how ``curses.window.addch``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800632uses optional groups to make the first two parameters and the last
633parameter optional::
634
Larry Hastings61272b72014-01-07 12:41:53 -0800635 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800636
637 curses.window.addch
638
639 [
640 x: int
641 X-coordinate.
642 y: int
643 Y-coordinate.
644 ]
645
646 ch: object
647 Character to add.
648
649 [
650 attr: long
651 Attributes for the character.
652 ]
653 /
654
655 ...
656
657
658Notes:
659
660* For every optional group, one additional parameter will be passed into the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800661 impl function representing the group. The parameter will be an int named
662 ``group_{direction}_{number}``,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800663 where ``{direction}`` is either ``right`` or ``left`` depending on whether the group
664 is before or after the required parameters, and ``{number}`` is a monotonically
665 increasing number (starting at 1) indicating how far away the group is from
666 the required parameters. When the impl is called, this parameter will be set
667 to zero if this group was unused, and set to non-zero if this group was used.
668 (By used or unused, I mean whether or not the parameters received arguments
669 in this invocation.)
670
671* If there are no required arguments, the optional groups will behave
Larry Hastings6d2ea212014-01-05 02:50:45 -0800672 as if they're to the right of the required arguments.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800673
674* In the case of ambiguity, the argument parsing code
675 favors parameters on the left (before the required parameters).
676
Larry Hastings6d2ea212014-01-05 02:50:45 -0800677* Optional groups can only contain positional-only parameters.
678
Larry Hastings78cf85c2014-01-04 12:44:57 -0800679* Optional groups are *only* intended for legacy code. Please do not
680 use optional groups for new code.
681
682
683Using real Argument Clinic converters, instead of "legacy converters"
684---------------------------------------------------------------------
685
686To save time, and to minimize how much you need to learn
687to achieve your first port to Argument Clinic, the walkthrough above tells
Larry Hastings6d2ea212014-01-05 02:50:45 -0800688you to use "legacy converters". "Legacy converters" are a convenience,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800689designed explicitly to make porting existing code to Argument Clinic
Larry Hastings4a55fc52014-01-12 11:09:57 -0800690easier. And to be clear, their use is acceptable when porting code for
691Python 3.4.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800692
693However, in the long term we probably want all our blocks to
694use Argument Clinic's real syntax for converters. Why? A couple
695reasons:
696
697* The proper converters are far easier to read and clearer in their intent.
698* There are some format units that are unsupported as "legacy converters",
699 because they require arguments, and the legacy converter syntax doesn't
700 support specifying arguments.
701* In the future we may have a new argument parsing library that isn't
Larry Hastings6d2ea212014-01-05 02:50:45 -0800702 restricted to what :c:func:`PyArg_ParseTuple` supports; this flexibility
703 won't be available to parameters using legacy converters.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800704
Larry Hastings4a55fc52014-01-12 11:09:57 -0800705Therefore, if you don't mind a little extra effort, please use the normal
706converters instead of legacy converters.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800707
708In a nutshell, the syntax for Argument Clinic (non-legacy) converters
709looks like a Python function call. However, if there are no explicit
710arguments to the function (all functions take their default values),
711you may omit the parentheses. Thus ``bool`` and ``bool()`` are exactly
Larry Hastings6d2ea212014-01-05 02:50:45 -0800712the same converters.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800713
Larry Hastings6d2ea212014-01-05 02:50:45 -0800714All arguments to Argument Clinic converters are keyword-only.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800715All Argument Clinic converters accept the following arguments:
716
Larry Hastings2a727912014-01-16 11:32:01 -0800717 ``c_default``
718 The default value for this parameter when defined in C.
719 Specifically, this will be the initializer for the variable declared
720 in the "parse function". See :ref:`the section on default values <default_values>`
721 for how to use this.
722 Specified as a string.
Larry Hastings4a55fc52014-01-12 11:09:57 -0800723
Larry Hastings2a727912014-01-16 11:32:01 -0800724 ``annotation``
725 The annotation value for this parameter. Not currently supported,
726 because PEP 8 mandates that the Python library may not use
727 annotations.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800728
Larry Hastings2a727912014-01-16 11:32:01 -0800729In addition, some converters accept additional arguments. Here is a list
730of these arguments, along with their meanings:
Larry Hastings78cf85c2014-01-04 12:44:57 -0800731
Larry Hastings2a727912014-01-16 11:32:01 -0800732 ``bitwise``
733 Only supported for unsigned integers. The native integer value of this
734 Python argument will be written to the parameter without any range checking,
735 even for negative values.
Larry Hastings4a55fc52014-01-12 11:09:57 -0800736
Larry Hastings2a727912014-01-16 11:32:01 -0800737 ``converter``
738 Only supported by the ``object`` converter. Specifies the name of a
739 :ref:`C "converter function" <o_ampersand>`
740 to use to convert this object to a native type.
741
742 ``encoding``
743 Only supported for strings. Specifies the encoding to use when converting
744 this string from a Python str (Unicode) value into a C ``char *`` value.
745
746 ``length``
747 Only supported for strings. If true, requests that the length of the
748 string be passed in to the impl function, just after the string parameter,
749 in a parameter named ``<parameter_name>_length``.
750
751 ``nullable``
752 Only supported for strings. If true, this parameter may also be set to
753 ``None``, in which case the C parameter will be set to ``NULL``.
754
755 ``subclass_of``
756 Only supported for the ``object`` converter. Requires that the Python
757 value be a subclass of a Python type, as expressed in C.
758
759 ``types``
760 Only supported for the ``object`` (and ``self``) converter. Specifies
761 the C type that will be used to declare the variable. Default value is
762 ``"PyObject *"``.
763
764 ``types``
765 A string containing a list of Python types (and possibly pseudo-types);
766 this restricts the allowable Python argument to values of these types.
767 (This is not a general-purpose facility; as a rule it only supports
768 specific lists of types as shown in the legacy converter table.)
769
770 ``zeroes``
771 Only supported for strings. If true, embedded NUL bytes (``'\\0'``) are
772 permitted inside the value.
773
774Please note, not every possible combination of arguments will work.
775Often these arguments are implemented internally by specific ``PyArg_ParseTuple``
776*format units*, with specific behavior. For example, currently you cannot
777call ``str`` and pass in ``zeroes=True`` without also specifying an ``encoding``;
778although it's perfectly reasonable to think this would work, these semantics don't
779map to any existing format unit. So Argument Clinic doesn't support it. (Or, at
780least, not yet.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800781
782Below is a table showing the mapping of legacy converters into real
783Argument Clinic converters. On the left is the legacy converter,
784on the right is the text you'd replace it with.
785
786========= =================================================================================
787``'B'`` ``byte(bitwise=True)``
788``'b'`` ``byte``
789``'c'`` ``char``
790``'C'`` ``int(types='str')``
791``'d'`` ``double``
792``'D'`` ``Py_complex``
793``'es#'`` ``str(encoding='name_of_encoding', length=True, zeroes=True)``
794``'es'`` ``str(encoding='name_of_encoding')``
795``'et#'`` ``str(encoding='name_of_encoding', types='bytes bytearray str', length=True)``
796``'et'`` ``str(encoding='name_of_encoding', types='bytes bytearray str')``
797``'f'`` ``float``
798``'h'`` ``short``
Larry Hastings4a55fc52014-01-12 11:09:57 -0800799``'H'`` ``unsigned_short(bitwise=True)``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800800``'i'`` ``int``
Larry Hastings4a55fc52014-01-12 11:09:57 -0800801``'I'`` ``unsigned_int(bitwise=True)``
802``'k'`` ``unsigned_long(bitwise=True)``
803``'K'`` ``unsigned_PY_LONG_LONG(bitwise=True)``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800804``'L'`` ``PY_LONG_LONG``
805``'n'`` ``Py_ssize_t``
Larry Hastings77561cc2014-01-07 12:13:13 -0800806``'O!'`` ``object(subclass_of='&PySomething_Type')``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800807``'O&'`` ``object(converter='name_of_c_function')``
808``'O'`` ``object``
809``'p'`` ``bool``
810``'s#'`` ``str(length=True)``
811``'S'`` ``PyBytesObject``
812``'s'`` ``str``
813``'s*'`` ``Py_buffer(types='str bytes bytearray buffer')``
814``'u#'`` ``Py_UNICODE(length=True)``
815``'u'`` ``Py_UNICODE``
816``'U'`` ``unicode``
817``'w*'`` ``Py_buffer(types='bytearray rwbuffer')``
Larry Hastings2a727912014-01-16 11:32:01 -0800818``'y#'`` ``str(types='bytes', length=True)``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800819``'Y'`` ``PyByteArrayObject``
Larry Hastings2a727912014-01-16 11:32:01 -0800820``'y'`` ``str(types='bytes')``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800821``'y*'`` ``Py_buffer``
822``'Z#'`` ``Py_UNICODE(nullable=True, length=True)``
823``'z#'`` ``str(nullable=True, length=True)``
824``'Z'`` ``Py_UNICODE(nullable=True)``
825``'z'`` ``str(nullable=True)``
826``'z*'`` ``Py_buffer(types='str bytes bytearray buffer', nullable=True)``
827========= =================================================================================
828
829As an example, here's our sample ``pickle.Pickler.dump`` using the proper
830converter::
831
Larry Hastings61272b72014-01-07 12:41:53 -0800832 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800833 pickle.Pickler.dump
834
835 obj: object
836 The object to be pickled.
837 /
838
839 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800840 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800841
842Argument Clinic will show you all the converters it has
843available. For each converter it'll show you all the parameters
844it accepts, along with the default value for each parameter.
845Just run ``Tools/clinic/clinic.py --converters`` to see the full list.
846
Larry Hastings4a55fc52014-01-12 11:09:57 -0800847Py_buffer
848---------
849
850When using the ``Py_buffer`` converter
Larry Hastings0191be32014-01-12 13:57:36 -0800851(or the ``'s*'``, ``'w*'``, ``'*y'``, or ``'z*'`` legacy converters),
852you *must* not call :c:func:`PyBuffer_Release` on the provided buffer.
853Argument Clinic generates code that does it for you (in the parsing function).
854
Larry Hastings4a55fc52014-01-12 11:09:57 -0800855
Larry Hastings78cf85c2014-01-04 12:44:57 -0800856
857Advanced converters
858-------------------
859
860Remeber those format units you skipped for your first
861time because they were advanced? Here's how to handle those too.
862
863The trick is, all those format units take arguments--either
864conversion functions, or types, or strings specifying an encoding.
865(But "legacy converters" don't support arguments. That's why we
866skipped them for your first function.) The argument you specified
867to the format unit is now an argument to the converter; this
Larry Hastings77561cc2014-01-07 12:13:13 -0800868argument is either ``converter`` (for ``O&``), ``subclass_of`` (for ``O!``),
Larry Hastings78cf85c2014-01-04 12:44:57 -0800869or ``encoding`` (for all the format units that start with ``e``).
870
Larry Hastings77561cc2014-01-07 12:13:13 -0800871When using ``subclass_of``, you may also want to use the other
872custom argument for ``object()``: ``type``, which lets you set the type
873actually used for the parameter. For example, if you want to ensure
874that the object is a subclass of ``PyUnicode_Type``, you probably want
875to use the converter ``object(type='PyUnicodeObject *', subclass_of='&PyUnicode_Type')``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800876
Larry Hastings77561cc2014-01-07 12:13:13 -0800877One possible problem with using Argument Clinic: it takes away some possible
878flexibility for the format units starting with ``e``. When writing a
879``PyArg_Parse`` call by hand, you could theoretically decide at runtime what
Larry Hastings6d2ea212014-01-05 02:50:45 -0800880encoding string to pass in to :c:func:`PyArg_ParseTuple`. But now this string must
Larry Hastings77561cc2014-01-07 12:13:13 -0800881be hard-coded at Argument-Clinic-preprocessing-time. This limitation is deliberate;
882it made supporting this format unit much easier, and may allow for future optimizations.
883This restriction doesn't seem unreasonable; CPython itself always passes in static
Larry Hastings6d2ea212014-01-05 02:50:45 -0800884hard-coded encoding strings for parameters whose format units start with ``e``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800885
886
Larry Hastings2a727912014-01-16 11:32:01 -0800887.. _default_values:
888
889Parameter default values
890------------------------
891
892Default values for parameters can be any of a number of values.
893At their simplest, they can be string, int, or float literals::
894
895 foo: str = "abc"
896 bar: int = 123
897 bat: float = 45.6
898
899They can also use any of Python's built-in constants::
900
901 yep: bool = True
902 nope: bool = False
903 nada: object = None
904
905There's also special support for a default value of ``NULL``, and
906for simple expressions, documented in the following sections.
907
908
909The ``NULL`` default value
910--------------------------
911
912For string and object parameters, you can set them to ``None`` to indicate
913that there's no default. However, that means the C variable will be
914initialized to ``Py_None``. For convenience's sakes, there's a special
915value called ``NULL`` for just this reason: from Python's perspective it
916behaves like a default value of ``None``, but the C variable is initialized
917with ``NULL``.
918
919Expressions specified as default values
920---------------------------------------
921
922The default value for a parameter can be more than just a literal value.
923It can be an entire expression, using math operators and looking up attributes
924on objects. However, this support isn't exactly simple, because of some
925non-obvious semantics.
926
927Consider the following example::
928
929 foo: Py_ssize_t = sys.maxsize - 1
930
931``sys.maxsize`` can have different values on different platforms. Therefore
932Argument Clinic can't simply evaluate that expression locally and hard-code it
933in C. So it stores the default in such a way that it will get evaluated at
934runtime, when the user asks for the function's signature.
935
936What namespace is available when the expression is evaluated? It's evaluated
937in the context of the module the builtin came from. So, if your module has an
938attribute called "``max_widgets``", you may simply use it::
939
940 foo: Py_ssize_t = max_widgets
941
942If the symbol isn't found in the current module, it fails over to looking in
943``sys.modules``. That's how it can find ``sys.maxsize`` for example. (Since you
944don't know in advance what modules the user will load into their interpreter,
945it's best to restrict yourself to modules that are preloaded by Python itself.)
946
947Evaluating default values only at runtime means Argument Clinic can't compute
948the correct equivalent C default value. So you need to tell it explicitly.
949When you use an expression, you must also specify the equivalent expression
950in C, using the ``c_default`` parameter to the converter::
951
952 foo: Py_ssize_t(c_default="PY_SSIZE_T_MAX - 1") = sys.maxsize - 1
953
954Another complication: Argument Clinic can't know in advance whether or not the
955expression you supply is valid. It parses it to make sure it looks legal, but
956it can't *actually* know. You must be very careful when using expressions to
957specify values that are guaranteed to be valid at runtime!
958
959Finally, because expressions must be representable as static C values, there
960are many restrictions on legal expressions. Here's a list of Python features
961you're not permitted to use:
962
963* Function calls.
964* Inline if statements (``3 if foo else 5``).
965* Automatic sequence unpacking (``*[1, 2, 3]``).
966* List/set/dict comprehensions and generator expressions.
967* Tuple/list/set/dict literals.
968
969
970
Larry Hastings78cf85c2014-01-04 12:44:57 -0800971Using a return converter
972------------------------
973
974By default the impl function Argument Clinic generates for you returns ``PyObject *``.
975But your C function often computes some C type, then converts it into the ``PyObject *``
976at the last moment. Argument Clinic handles converting your inputs from Python types
977into native C types--why not have it convert your return value from a native C type
978into a Python type too?
979
980That's what a "return converter" does. It changes your impl function to return
981some C type, then adds code to the generated (non-impl) function to handle converting
982that value into the appropriate ``PyObject *``.
983
984The syntax for return converters is similar to that of parameter converters.
985You specify the return converter like it was a return annotation on the
986function itself. Return converters behave much the same as parameter converters;
987they take arguments, the arguments are all keyword-only, and if you're not changing
988any of the default arguments you can omit the parentheses.
989
990(If you use both ``"as"`` *and* a return converter for your function,
991the ``"as"`` should come before the return converter.)
992
993There's one additional complication when using return converters: how do you
994indicate an error has occured? Normally, a function returns a valid (non-``NULL``)
995pointer for success, and ``NULL`` for failure. But if you use an integer return converter,
996all integers are valid. How can Argument Clinic detect an error? Its solution: each return
997converter implicitly looks for a special value that indicates an error. If you return
998that value, and an error has been set (``PyErr_Occurred()`` returns a true
999value), then the generated code will propogate the error. Otherwise it will
1000encode the value you return like normal.
1001
1002Currently Argument Clinic supports only a few return converters::
1003
Larry Hastings4a55fc52014-01-12 11:09:57 -08001004 bool
Larry Hastings78cf85c2014-01-04 12:44:57 -08001005 int
Larry Hastings4a55fc52014-01-12 11:09:57 -08001006 unsigned int
Larry Hastings78cf85c2014-01-04 12:44:57 -08001007 long
Larry Hastings4a55fc52014-01-12 11:09:57 -08001008 unsigned int
1009 size_t
Larry Hastings78cf85c2014-01-04 12:44:57 -08001010 Py_ssize_t
Larry Hastings4a55fc52014-01-12 11:09:57 -08001011 float
1012 double
Larry Hastings78cf85c2014-01-04 12:44:57 -08001013 DecodeFSDefault
1014
1015None of these take parameters. For the first three, return -1 to indicate
1016error. For ``DecodeFSDefault``, the return type is ``char *``; return a NULL
1017pointer to indicate an error.
1018
Larry Hastings4a55fc52014-01-12 11:09:57 -08001019(There's also an experimental ``NoneType`` converter, which lets you
1020return ``Py_None`` on success or ``NULL`` on failure, without having
1021to increment the reference count on ``Py_None``. I'm not sure it adds
1022enough clarity to be worth using.)
1023
Larry Hastings6d2ea212014-01-05 02:50:45 -08001024To see all the return converters Argument Clinic supports, along with
1025their parameters (if any),
1026just run ``Tools/clinic/clinic.py --converters`` for the full list.
1027
1028
Larry Hastings4a714d42014-01-14 22:22:41 -08001029Cloning existing functions
1030--------------------------
1031
1032If you have a number of functions that look similar, you may be able to
1033use Clinic's "clone" feature. When you clone an existing function,
1034you reuse:
1035
1036* its parameters, including
1037
1038 * their names,
1039
1040 * their converters, with all parameters,
1041
1042 * their default values,
1043
1044 * their per-parameter docstrings,
1045
1046 * their *kind* (whether they're positional only,
1047 positional or keyword, or keyword only), and
1048
1049* its return converter.
1050
1051The only thing not copied from the original function is its docstring;
1052the syntax allows you to specify a new docstring.
1053
1054Here's the syntax for cloning a function::
1055
1056 /*[clinic input]
1057 module.class.new_function [as c_basename] = module.class.existing_function
1058
1059 Docstring for new_function goes here.
1060 [clinic start generated code]*/
1061
1062(The functions can be in different modules or classes. I wrote
1063``module.class`` in the sample just to illustrate that you must
1064use the full path to *both* functions.)
1065
1066Sorry, there's no syntax for partially-cloning a function, or cloning a function
1067then modifying it. Cloning is an all-or nothing proposition.
1068
1069Also, the function you are cloning from must have been previously defined
1070in the current file.
1071
Larry Hastings78cf85c2014-01-04 12:44:57 -08001072Calling Python code
1073-------------------
1074
1075The rest of the advanced topics require you to write Python code
Larry Hastings6d2ea212014-01-05 02:50:45 -08001076which lives inside your C file and modifies Argument Clinic's
1077runtime state. This is simple: you simply define a Python block.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001078
1079A Python block uses different delimiter lines than an Argument
1080Clinic function block. It looks like this::
1081
Larry Hastings61272b72014-01-07 12:41:53 -08001082 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001083 # python code goes here
Larry Hastings61272b72014-01-07 12:41:53 -08001084 [python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001085
1086All the code inside the Python block is executed at the
1087time it's parsed. All text written to stdout inside the block
1088is redirected into the "output" after the block.
1089
1090As an example, here's a Python block that adds a static integer
1091variable to the C code::
1092
Larry Hastings61272b72014-01-07 12:41:53 -08001093 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001094 print('static int __ignored_unused_variable__ = 0;')
Larry Hastings61272b72014-01-07 12:41:53 -08001095 [python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001096 static int __ignored_unused_variable__ = 0;
1097 /*[python checksum:...]*/
1098
1099
1100Using a "self converter"
1101------------------------
1102
1103Argument Clinic automatically adds a "self" parameter for you
1104using a default converter. However, you can override
1105Argument Clinic's converter and specify one yourself.
1106Just add your own ``self`` parameter as the first parameter in a
1107block, and ensure that its converter is an instance of
1108``self_converter`` or a subclass thereof.
1109
1110What's the point? This lets you automatically cast ``self``
Larry Hastings77561cc2014-01-07 12:13:13 -08001111from ``PyObject *`` to a custom type, just like ``object()``
1112does with its ``type`` parameter.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001113
1114How do you specify the custom type you want to cast ``self`` to?
1115If you only have one or two functions with the same type for ``self``,
1116you can directly use Argument Clinic's existing ``self`` converter,
1117passing in the type you want to use as the ``type`` parameter::
1118
Larry Hastings61272b72014-01-07 12:41:53 -08001119 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001120
1121 _pickle.Pickler.dump
1122
1123 self: self(type="PicklerObject *")
1124 obj: object
1125 /
1126
1127 Write a pickled representation of the given object to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -08001128 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001129
1130On the other hand, if you have a lot of functions that will use the same
1131type for ``self``, it's best to create your own converter, subclassing
1132``self_converter`` but overwriting the ``type`` member::
1133
Zachary Warec1cb2272014-01-09 21:41:23 -06001134 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001135 class PicklerObject_converter(self_converter):
1136 type = "PicklerObject *"
Zachary Warec1cb2272014-01-09 21:41:23 -06001137 [python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001138
Larry Hastings61272b72014-01-07 12:41:53 -08001139 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001140
1141 _pickle.Pickler.dump
1142
1143 self: PicklerObject
1144 obj: object
1145 /
1146
1147 Write a pickled representation of the given object to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -08001148 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001149
1150
1151
1152Writing a custom converter
1153--------------------------
1154
1155As we hinted at in the previous section... you can write your own converters!
1156A converter is simply a Python class that inherits from ``CConverter``.
1157The main purpose of a custom converter is if you have a parameter using
1158the ``O&`` format unit--parsing this parameter means calling
Larry Hastings6d2ea212014-01-05 02:50:45 -08001159a :c:func:`PyArg_ParseTuple` "converter function".
Larry Hastings78cf85c2014-01-04 12:44:57 -08001160
1161Your converter class should be named ``*something*_converter``.
1162If the name follows this convention, then your converter class
1163will be automatically registered with Argument Clinic; its name
1164will be the name of your class with the ``_converter`` suffix
Larry Hastings6d2ea212014-01-05 02:50:45 -08001165stripped off. (This is accomplished with a metaclass.)
Larry Hastings78cf85c2014-01-04 12:44:57 -08001166
1167You shouldn't subclass ``CConverter.__init__``. Instead, you should
1168write a ``converter_init()`` function. ``converter_init()``
1169always accepts a ``self`` parameter; after that, all additional
1170parameters *must* be keyword-only. Any arguments passed in to
1171the converter in Argument Clinic will be passed along to your
1172``converter_init()``.
1173
1174There are some additional members of ``CConverter`` you may wish
1175to specify in your subclass. Here's the current list:
1176
1177``type``
1178 The C type to use for this variable.
1179 ``type`` should be a Python string specifying the type, e.g. ``int``.
1180 If this is a pointer type, the type string should end with ``' *'``.
1181
1182``default``
1183 The Python default value for this parameter, as a Python value.
1184 Or the magic value ``unspecified`` if there is no default.
1185
Larry Hastings78cf85c2014-01-04 12:44:57 -08001186``py_default``
1187 ``default`` as it should appear in Python code,
1188 as a string.
1189 Or ``None`` if there is no default.
1190
1191``c_default``
1192 ``default`` as it should appear in C code,
1193 as a string.
1194 Or ``None`` if there is no default.
1195
1196``c_ignored_default``
1197 The default value used to initialize the C variable when
1198 there is no default, but not specifying a default may
Larry Hastings6d2ea212014-01-05 02:50:45 -08001199 result in an "uninitialized variable" warning. This can
Larry Hastings78cf85c2014-01-04 12:44:57 -08001200 easily happen when using option groups--although
Larry Hastings6d2ea212014-01-05 02:50:45 -08001201 properly-written code will never actually use this value,
1202 the variable does get passed in to the impl, and the
1203 C compiler will complain about the "use" of the
1204 uninitialized value. This value should always be a
1205 non-empty string.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001206
1207``converter``
1208 The name of the C converter function, as a string.
1209
1210``impl_by_reference``
1211 A boolean value. If true,
1212 Argument Clinic will add a ``&`` in front of the name of
1213 the variable when passing it into the impl function.
1214
1215``parse_by_reference``
1216 A boolean value. If true,
1217 Argument Clinic will add a ``&`` in front of the name of
Larry Hastings6d2ea212014-01-05 02:50:45 -08001218 the variable when passing it into :c:func:`PyArg_ParseTuple`.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001219
1220
1221Here's the simplest example of a custom converter, from ``Modules/zlibmodule.c``::
1222
Larry Hastings61272b72014-01-07 12:41:53 -08001223 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001224
1225 class uint_converter(CConverter):
1226 type = 'unsigned int'
1227 converter = 'uint_converter'
1228
Larry Hastings61272b72014-01-07 12:41:53 -08001229 [python start generated code]*/
1230 /*[python end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001231
Larry Hastings6d2ea212014-01-05 02:50:45 -08001232This block adds a converter to Argument Clinic named ``uint``. Parameters
Larry Hastings78cf85c2014-01-04 12:44:57 -08001233declared as ``uint`` will be declared as type ``unsigned int``, and will
Larry Hastings6d2ea212014-01-05 02:50:45 -08001234be parsed by the ``'O&'`` format unit, which will call the ``uint_converter``
1235converter function.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001236``uint`` variables automatically support default values.
1237
1238More sophisticated custom converters can insert custom C code to
1239handle initialization and cleanup.
1240You can see more examples of custom converters in the CPython
1241source tree; grep the C files for the string ``CConverter``.
1242
1243Writing a custom return converter
1244---------------------------------
1245
1246Writing a custom return converter is much like writing
Larry Hastings6d2ea212014-01-05 02:50:45 -08001247a custom converter. Except it's somewhat simpler, because return
Larry Hastings78cf85c2014-01-04 12:44:57 -08001248converters are themselves much simpler.
1249
1250Return converters must subclass ``CReturnConverter``.
1251There are no examples yet of custom return converters,
1252because they are not widely used yet. If you wish to
1253write your own return converter, please read ``Tools/clinic/clinic.py``,
1254specifically the implementation of ``CReturnConverter`` and
1255all its subclasses.
1256
Larry Hastings4a55fc52014-01-12 11:09:57 -08001257METH_O and METH_NOARGS
1258----------------------------------------------
1259
1260To convert a function using ``METH_O``, make sure the function's
1261single argument is using the ``object`` converter, and mark the
1262arguments as positional-only::
1263
1264 /*[clinic input]
1265 meth_o_sample
1266
1267 argument: object
1268 /
1269 [clinic start generated code]*/
1270
1271
1272To convert a function using ``METH_NOARGS``, just don't specify
1273any arguments.
1274
1275You can still use a self converter, a return converter, and specify
1276a ``type`` argument to the object converter for ``METH_O``.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001277
Larry Hastings2a727912014-01-16 11:32:01 -08001278The #ifdef trick
1279----------------------------------------------
1280
1281If you're converting a function that isn't available on all platforms,
1282there's a trick you can use to make life a little easier. The existing
1283code probably looks like this::
1284
1285 #ifdef HAVE_FUNCTIONNAME
1286 static module_functionname(...)
1287 {
1288 ...
1289 }
1290 #endif /* HAVE_FUNCTIONNAME */
1291
1292And then in the ``PyMethodDef`` structure at the bottom you'll have::
1293
1294 #ifdef HAVE_FUNCTIONNAME
1295 {'functionname', ... },
1296 #endif /* HAVE_FUNCTIONNAME */
1297
1298In this scenario, you should change the code to look like the following::
1299
1300 #ifdef HAVE_FUNCTIONNAME
1301 /*[clinic input]
1302 module.functionname
1303 ...
1304 [clinic start generated code]*/
1305 static module_functionname(...)
1306 {
1307 ...
1308 }
1309 #endif /* HAVE_FUNCTIONNAME */
1310
1311Run Argument Clinic on the code in this state, then refresh the file in
1312your editor. Now you'll have the generated code, including the #define
1313for the ``PyMethodDef``, like so::
1314
1315 #ifdef HAVE_FUNCTIONNAME
1316 /*[clinic input]
1317 ...
1318 [clinic start generated code]*/
1319 ...
1320 #define MODULE_FUNCTIONNAME \
1321 {'functionname', ... },
1322 ...
1323 /*[clinic end generated code: checksum=...]*/
1324 static module_functionname(...)
1325 {
1326 ...
1327 }
1328 #endif /* HAVE_FUNCTIONNAME */
1329
1330Change the #endif at the bottom as follows::
1331
1332 #else
1333 #define MODULE_FUNCTIONNAME
1334 #endif /* HAVE_FUNCTIONNAME */
1335
1336Now you can remove the #ifdefs around the ``PyMethodDef`` structure
1337at the end, and replace those three lines with ``MODULE_FUNCTIONNAME``.
1338If the function is available, the macro turns into the ``PyMethodDef``
1339static value, including the trailing comma; if the function isn't
1340available, the macro turns into nothing. Perfect!
1341
1342(This is the preferred approach for optional functions; in the future,
1343Argument Clinic may generate the entire ``PyMethodDef`` structure.)
1344
Larry Hastingsbebf7352014-01-17 17:47:17 -08001345
1346Changing and redirecting Clinic's output
1347----------------------------------------
1348
1349It can be inconvenient to have Clinic's output interspersed with
1350your conventional hand-edited C code. Luckily, Clinic is configurable:
1351you can buffer up its output for printing later (or earlier!), or write
1352its output to a separate file. You can also add a prefix or suffix to
1353every line of Clinic's generated output.
1354
1355While changing Clinic's output in this manner can be a boon to readability,
1356it may result in Clinic code using types before they are defined, or
1357your code attempting to use Clinic-generated code befire it is defined.
1358These problems can be easily solved by rearranging the declarations in your file,
1359or moving where Clinic's generated code goes. (This is why the default behavior
1360of Clinic is to output everything into the current block; while many people
1361consider this hampers readability, it will never require rearranging your
1362code to fix definition-before-use problems.)
1363
1364Let's start with defining some terminology:
1365
1366*field*
1367 A field, in this context, is a subsection of Clinic's output.
1368 For example, the ``#define`` for the ``PyMethodDef`` structure
1369 is a field, called ``methoddef_define``. Clinic has seven
1370 different fields it can output per function definition::
1371
1372 docstring_prototype
1373 docstring_definition
1374 methoddef_define
1375 impl_prototype
1376 parser_prototype
1377 parser_definition
1378 impl_definition
1379
1380 All the names are of the form ``"<a>_<b>"``,
1381 where ``"<a>"`` is the semantic object represented (the parsing function,
1382 the impl function, the docstring, or the methoddef structure) and ``"<b>"``
1383 represents what kind of statement the field is. Field names that end in
1384 ``"_prototype"``
1385 represent forward declarations of that thing, without the actual body/data
1386 of the thing; field names that end in ``"_definition"`` represent the actual
1387 definition of the thing, with the body/data of the thing. (``"methoddef"``
1388 is special, it's the only one that ends with ``"_define"``, representing that
1389 it's a preprocessor #define.)
1390
1391*destination*
1392 A destination is a place Clinic can write output to. There are
1393 five built-in destinations:
1394
1395 ``block``
1396 The default destination: printed in the output section of
1397 the current Clinic block.
1398
1399 ``buffer``
1400 A text buffer where you can save text for later. Text sent
1401 here is appended to the end of any exsiting text. It's an
1402 error to have any text left in the buffer when Clinic finishes
1403 processing a file.
1404
1405 ``file``
1406 A separate "clinic file" that will be created automatically by Clinic.
1407 The filename chosen for the file is ``{basename}.clinic{extension}``,
1408 where ``basename`` and ``extension`` were assigned the output
1409 from ``os.path.splitext()`` run on the current file. (Example:
1410 the ``file`` destination for ``_pickle.c`` would be written to
1411 ``_pickle.clinic.c``.)
1412
1413 **Important: When using a** ``file`` **destination, you**
1414 *must check in* **the generated file!**
1415
1416 ``two-pass``
1417 A buffer like ``buffer``. However, a two-pass buffer can only
1418 be written once, and it prints out all text sent to it during
1419 all of processing, even from Clinic blocks *after* the
1420
1421 ``suppress``
1422 The text is suppressed--thrown away.
1423
1424
1425Clinic defines five new directives that let you reconfigure its output.
1426
1427The first new directive is ``dump``::
1428
1429 dump <destination>
1430
1431This dumps the current contents of the named destination into the output of
1432the current block, and empties it. This only works with ``buffer`` and
1433``two-pass`` destinations.
1434
1435The second new directive is ``output``. The most basic form of ``output``
1436is like this::
1437
1438 output <field> <destination>
1439
1440This tells Clinic to output *field* to *destination*. ``output`` also
1441supports a special meta-destination, called ``everything``, which tells
1442Clinic to output *all* fields to that *destination*.
1443
1444``output`` has a number of other functions::
1445
1446 output push
1447 output pop
1448 output preset <preset>
1449
1450
1451``output push`` and ``output pop`` allow you to push and pop
1452configurations on an internal configuration stack, so that you
1453can temporarily modify the output configuration, then easily restore
1454the previous configuration. Simply push before your change to save
1455the current configuration, then pop when you wish to restore the
1456previous configuration.
1457
1458``output preset`` sets Clinic's output to one of several built-in
1459preset configurations, as follows:
1460
1461 ``original``
1462 Clinic's starting configuration.
1463
1464 Suppress the ``parser_prototype``
1465 and ``docstring_prototype``, write everything else to ``block``.
1466
1467 ``file``
1468 Designed to write everything to the "clinic file" that it can.
1469 You then ``#include`` this file near the top of your file.
1470 You may need to rearrange your file to make this work, though
1471 usually this just means creating forward declarations for various
1472 ``typedef`` and ``PyTypeObject`` definitions.
1473
1474 Suppress the ``parser_prototype``
1475 and ``docstring_prototype``, write the ``impl_definition`` to
1476 ``block``, and write everything else to ``file``.
1477
1478 ``buffer``
1479 Save up all most of the output from Clinic, to be written into
1480 your file near the end. For Python files implementing modules
1481 or builtin types, it's recommended that you dump the buffer
1482 just above the static structures for your module or
1483 builtin type; these are normally very near the end. Using
1484 ``buffer`` may require even more editing than ``file``, if
1485 your file has static ``PyMethodDef`` arrays defined in the
1486 middle of the file.
1487
1488 Suppress the ``parser_prototype``, ``impl_prototype``,
1489 and ``docstring_prototype``, write the ``impl_definition`` to
1490 ``block``, and write everything else to ``file``.
1491
1492 ``two-pass``
1493 Similar to the ``buffer`` preset, but writes forward declarations to
1494 the ``two-pass`` buffer, and definitions to the ``buffer``.
1495 This is similar to the ``buffer`` preset, but may require
1496 less editing than ``buffer``. Dump the ``two-pass`` buffer
1497 near the top of your file, and dump the ``buffer`` near
1498 the end just like you would when using the ``buffer`` preset.
1499
1500 Suppresses the ``impl_prototype``, write the ``impl_definition``
1501 to ``block``, write ``docstring_prototype``, ``methoddef_define``,
1502 and ``parser_prototype`` to ``two-pass``, write everything else
1503 to ``buffer``.
1504
1505 ``partial-buffer``
1506 Similar to the ``buffer`` preset, but writes more things to ``block``,
1507 only writing the really big chunks of generated code to ``buffer``.
1508 This avoids the definition-before-use problem of ``buffer`` completely,
1509 at the small cost of having slightly more stuff in the block's output.
1510 Dump the ``buffer`` near the end, just like you would when using
1511 the ``buffer`` preset.
1512
1513 Suppresses the ``impl_prototype``, write the ``docstring_definition``
1514 and ``parser_defintion`` to ``buffer``, write everything else to ``block``.
1515
1516The third new directive is ``destination``::
1517
1518 destination <name> <command> [...]
1519
1520This performs an operation on the destination named ``name``.
1521
1522There are two defined subcommands: ``new`` and ``clear``.
1523
1524The ``new`` subcommand works like this::
1525
1526 destination <name> new <type>
1527
1528This creates a new destination with name ``<name>`` and type ``<type>``.
1529
1530There are five destination types::
1531
1532 ``suppress``
1533 Throws the text away.
1534
1535 ``block``
1536 Writes the text to the current block. This is what Clinic
1537 originally did.
1538
1539 ``buffer``
1540 A simple text buffer, like the "buffer" builtin destination above.
1541
1542 ``file``
1543 A text file. The file destination takes an extra argument,
1544 a template to use for building the filename, like so:
1545
1546 destination <name> new <type> <file_template>
1547
1548 The template can use three strings internally that will be replaced
1549 by bits of the filename:
1550
1551 {filename}
1552 The full filename.
1553 {basename}
1554 Everything up to but not including the last '.'.
1555 {extension}
1556 The last '.' and everything after it.
1557
1558 If there are no periods in the filename, {basename} and {filename}
1559 are the same, and {extension} is empty. "{basename}{extension}"
1560 is always exactly the same as "{filename}"."
1561
1562 ``two-pass``
1563 A two-pass buffer, like the "two-pass" builtin destination above.
1564
1565
1566The ``clear`` subcommand works like this::
1567
1568 destination <name> clear
1569
1570It removes all the accumulated text up to this point in the destination.
1571(I don't know what you'd need this for, but I thought maybe it'd be
1572useful while someone's experimenting.)
1573
1574The fourth new directive is ``set``::
1575
1576 set line_prefix "string"
1577 set line_suffix "string"
1578
1579``set`` lets you set two internal variables in Clinic.
1580``line_prefix`` is a string that will be prepended to every line of Clinic's output;
1581``line_suffix`` is a string that will be appended to every line of Clinic's output.
1582
1583Both of these suport two format strings:
1584
1585 ``{block comment start}``
1586 Turns into the string ``/*``, the start-comment text sequence for C files.
1587
1588 ``{block comment end}``
1589 Turns into the string ``*/``, the end-comment text sequence for C files.
1590
1591The final new directive is one you shouldn't need to use directly,
1592called ``preserve``::
1593
1594 preserve
1595
1596This tells Clinic that the current contents of the output should be kept, unmodifed.
1597This is used internally by Clinic when dumping output into ``file`` files; wrapping
1598it in a Clinic block lets Clinic use its existing checksum functionality to ensure
1599the file was not modified by hand before it gets overwritten.
1600
1601
1602Using Argument Clinic in Python files
Larry Hastings78cf85c2014-01-04 12:44:57 -08001603-------------------------------------
1604
1605It's actually possible to use Argument Clinic to preprocess Python files.
1606There's no point to using Argument Clinic blocks, of course, as the output
1607wouldn't make any sense to the Python interpreter. But using Argument Clinic
1608to run Python blocks lets you use Python as a Python preprocessor!
1609
1610Since Python comments are different from C comments, Argument Clinic
1611blocks embedded in Python files look slightly different. They look like this::
1612
Larry Hastings61272b72014-01-07 12:41:53 -08001613 #/*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001614 #print("def foo(): pass")
Larry Hastings61272b72014-01-07 12:41:53 -08001615 #[python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001616 def foo(): pass
1617 #/*[python checksum:...]*/