blob: e362631db6af614ef8ad0cfe6786bb52e5c25e83 [file] [log] [blame]
Ezio Melottia3642b62014-01-25 17:27:46 +02001**********************
Larry Hastings78cf85c2014-01-04 12:44:57 -08002Argument Clinic How-To
Ezio Melottia3642b62014-01-25 17:27:46 +02003**********************
Larry Hastings78cf85c2014-01-04 12:44:57 -08004
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 -080026The Goals Of Argument Clinic
27============================
28
29Argument Clinic's primary goal
30is to take over responsibility for all argument parsing code
31inside CPython. This means that, when you convert a function
32to work with Argument Clinic, that function should no longer
33do any of its own argument parsing--the code generated by
34Argument Clinic should be a "black box" to you, where CPython
35calls in at the top, and your code gets called at the bottom,
36with ``PyObject *args`` (and maybe ``PyObject *kwargs``)
37magically converted into the C variables and types you need.
38
39In order for Argument Clinic to accomplish its primary goal,
40it must be easy to use. Currently, working with CPython's
41argument parsing library is a chore, requiring maintaining
42redundant information in a surprising number of places.
43When you use Argument Clinic, you don't have to repeat yourself.
44
45Obviously, no one would want to use Argument Clinic unless
Larry Hastings537d7602014-01-18 01:08:50 -080046it's solving their problem--and without creating new problems of
Larry Hastingsbebf7352014-01-17 17:47:17 -080047its own.
Larry Hastings537d7602014-01-18 01:08:50 -080048So it's paramount that Argument Clinic generate correct code.
49It'd be nice if the code was faster, too, but at the very least
50it should not introduce a major speed regression. (Eventually Argument
51Clinic *should* make a major speedup possible--we could
52rewrite its code generator to produce tailor-made argument
53parsing code, rather than calling the general-purpose CPython
54argument parsing library. That would make for the fastest
55argument parsing possible!)
Larry Hastingsbebf7352014-01-17 17:47:17 -080056
57Additionally, Argument Clinic must be flexible enough to
58work with any approach to argument parsing. Python has
59some functions with some very strange parsing behaviors;
60Argument Clinic's goal is to support all of them.
61
62Finally, the original motivation for Argument Clinic was
63to provide introspection "signatures" for CPython builtins.
64It used to be, the introspection query functions would throw
65an exception if you passed in a builtin. With Argument
66Clinic, that's a thing of the past!
67
68One idea you should keep in mind, as you work with
69Argument Clinic: the more information you give it, the
70better job it'll be able to do.
71Argument Clinic is admittedly relatively simple right
72now. But as it evolves it will get more sophisticated,
73and it should be able to do many interesting and smart
74things with all the information you give it.
75
76
Larry Hastings78cf85c2014-01-04 12:44:57 -080077Basic Concepts And Usage
78========================
79
Larry Hastings6d2ea212014-01-05 02:50:45 -080080Argument Clinic ships with CPython; you'll find it in ``Tools/clinic/clinic.py``.
Larry Hastings78cf85c2014-01-04 12:44:57 -080081If you run that script, specifying a C file as an argument::
82
83 % python3 Tools/clinic/clinic.py foo.c
84
85Argument Clinic will scan over the file looking for lines that
86look exactly like this::
87
Larry Hastings61272b72014-01-07 12:41:53 -080088 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -080089
90When it finds one, it reads everything up to a line that looks
Larry Hastings61272b72014-01-07 12:41:53 -080091exactly like this::
Larry Hastings78cf85c2014-01-04 12:44:57 -080092
Larry Hastings61272b72014-01-07 12:41:53 -080093 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -080094
95Everything in between these two lines is input for Argument Clinic.
96All of these lines, including the beginning and ending comment
Larry Hastings6d2ea212014-01-05 02:50:45 -080097lines, are collectively called an Argument Clinic "block".
Larry Hastings78cf85c2014-01-04 12:44:57 -080098
99When Argument Clinic parses one of these blocks, it
100generates output. This output is rewritten into the C file
101immediately after the block, followed by a comment containing a checksum.
Larry Hastings6d2ea212014-01-05 02:50:45 -0800102The Argument Clinic block now looks like this::
Larry Hastings78cf85c2014-01-04 12:44:57 -0800103
Larry Hastings61272b72014-01-07 12:41:53 -0800104 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800105 ... clinic input goes here ...
Larry Hastings61272b72014-01-07 12:41:53 -0800106 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800107 ... clinic output goes here ...
Larry Hastings61272b72014-01-07 12:41:53 -0800108 /*[clinic end generated code: checksum=...]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800109
110If you run Argument Clinic on the same file a second time, Argument Clinic
111will discard the old output and write out the new output with a fresh checksum
112line. However, if the input hasn't changed, the output won't change either.
113
114You should never modify the output portion of an Argument Clinic block. Instead,
115change the input until it produces the output you want. (That's the purpose of the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800116checksum--to detect if someone changed the output, as these edits would be lost
117the next time Argument Clinic writes out fresh output.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800118
119For the sake of clarity, here's the terminology we'll use with Argument Clinic:
120
Larry Hastings61272b72014-01-07 12:41:53 -0800121* The first line of the comment (``/*[clinic input]``) is the *start line*.
122* The last line of the initial comment (``[clinic start generated code]*/``) is the *end line*.
123* The last line (``/*[clinic end generated code: checksum=...]*/``) is the *checksum line*.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800124* In between the start line and the end line is the *input*.
125* In between the end line and the checksum line is the *output*.
126* All the text collectively, from the start line to the checksum line inclusively,
127 is the *block*. (A block that hasn't been successfully processed by Argument
128 Clinic yet doesn't have output or a checksum line, but it's still considered
129 a block.)
130
131
Larry Hastings78cf85c2014-01-04 12:44:57 -0800132Converting Your First Function
133==============================
134
135The best way to get a sense of how Argument Clinic works is to
Larry Hastingsbebf7352014-01-17 17:47:17 -0800136convert a function to work with it. Here, then, are the bare
137minimum steps you'd need to follow to convert a function to
138work with Argument Clinic. Note that for code you plan to
139check in to CPython, you really should take the conversion farther,
140using some of the advanced concepts you'll see later on in
141the document (like "return converters" and "self converters").
142But we'll keep it simple for this walkthrough so you can learn.
143
144Let's dive in!
Larry Hastings78cf85c2014-01-04 12:44:57 -0800145
Larry Hastings6d2ea212014-01-05 02:50:45 -08001460. Make sure you're working with a freshly updated checkout
147 of the CPython trunk.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800148
Larry Hastings6d2ea212014-01-05 02:50:45 -08001491. Find a Python builtin that calls either :c:func:`PyArg_ParseTuple`
150 or :c:func:`PyArg_ParseTupleAndKeywords`, and hasn't been converted
151 to work with Argument Clinic yet.
Larry Hastings0e254102014-01-26 00:42:02 -0800152 For my example I'm using ``_pickle.Pickler.dump()``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800153
1542. If the call to the ``PyArg_Parse`` function uses any of the
155 following format units::
156
157 O&
158 O!
159 es
160 es#
161 et
162 et#
163
Larry Hastings6d2ea212014-01-05 02:50:45 -0800164 or if it has multiple calls to :c:func:`PyArg_ParseTuple`,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800165 you should choose a different function. Argument Clinic *does*
166 support all of these scenarios. But these are advanced
167 topics--let's do something simpler for your first function.
168
Larry Hastings4a55fc52014-01-12 11:09:57 -0800169 Also, if the function has multiple calls to :c:func:`PyArg_ParseTuple`
170 or :c:func:`PyArg_ParseTupleAndKeywords` where it supports different
171 types for the same argument, or if the function uses something besides
172 PyArg_Parse functions to parse its arguments, it probably
173 isn't suitable for conversion to Argument Clinic. Argument Clinic
174 doesn't support generic functions or polymorphic parameters.
175
Larry Hastings78cf85c2014-01-04 12:44:57 -08001763. Add the following boilerplate above the function, creating our block::
177
Larry Hastings61272b72014-01-07 12:41:53 -0800178 /*[clinic input]
179 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800180
1814. Cut the docstring and paste it in between the ``[clinic]`` lines,
182 removing all the junk that makes it a properly quoted C string.
183 When you're done you should have just the text, based at the left
184 margin, with no line wider than 80 characters.
185 (Argument Clinic will preserve indents inside the docstring.)
186
Larry Hastings2a727912014-01-16 11:32:01 -0800187 If the old docstring had a first line that looked like a function
188 signature, throw that line away. (The docstring doesn't need it
189 anymore--when you use ``help()`` on your builtin in the future,
190 the first line will be built automatically based on the function's
191 signature.)
192
Larry Hastings78cf85c2014-01-04 12:44:57 -0800193 Sample::
194
Larry Hastings61272b72014-01-07 12:41:53 -0800195 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800196 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800197 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800198
1995. If your docstring doesn't have a "summary" line, Argument Clinic will
200 complain. So let's make sure it has one. The "summary" line should
201 be a paragraph consisting of a single 80-column line
202 at the beginning of the docstring.
203
Larry Hastings6d2ea212014-01-05 02:50:45 -0800204 (Our example docstring consists solely of a summary line, so the sample
Larry Hastings78cf85c2014-01-04 12:44:57 -0800205 code doesn't have to change for this step.)
206
2076. Above the docstring, enter the name of the function, followed
208 by a blank line. This should be the Python name of the function,
209 and should be the full dotted path
210 to the function--it should start with the name of the module,
211 include any sub-modules, and if the function is a method on
212 a class it should include the class name too.
213
214 Sample::
215
Larry Hastings61272b72014-01-07 12:41:53 -0800216 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800217 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800218
219 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800220 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800221
2227. If this is the first time that module or class has been used with Argument
223 Clinic in this C file,
224 you must declare the module and/or class. Proper Argument Clinic hygiene
225 prefers declaring these in a separate block somewhere near the
226 top of the C file, in the same way that include files and statics go at
227 the top. (In our sample code we'll just show the two blocks next to
228 each other.)
229
Larry Hastings4a55fc52014-01-12 11:09:57 -0800230 The name of the class and module should be the same as the one
231 seen by Python. Check the name defined in the :c:type:`PyModuleDef`
232 or :c:type:`PyTypeObject` as appropriate.
233
Larry Hastings0e254102014-01-26 00:42:02 -0800234 When you declare a class, you must also specify two aspects of its type
235 in C: the type declaration you'd use for a pointer to an instance of
236 this class, and a pointer to the :c:type:`PyTypeObject` for this class.
237
238 Sample::
239
240 /*[clinic input]
241 module _pickle
242 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
243 [clinic start generated code]*/
244
245 /*[clinic input]
246 _pickle.Pickler.dump
247
248 Write a pickled representation of obj to the open file.
249 [clinic start generated code]*/
250
251
Larry Hastings4a55fc52014-01-12 11:09:57 -0800252
Larry Hastings78cf85c2014-01-04 12:44:57 -0800253
2548. Declare each of the parameters to the function. Each parameter
255 should get its own line. All the parameter lines should be
256 indented from the function name and the docstring.
257
258 The general form of these parameter lines is as follows::
259
260 name_of_parameter: converter
261
262 If the parameter has a default value, add that after the
263 converter::
264
265 name_of_parameter: converter = default_value
266
Larry Hastings2a727912014-01-16 11:32:01 -0800267 Argument Clinic's support for "default values" is quite sophisticated;
268 please see :ref:`the section below on default values <default_values>`
269 for more information.
270
Larry Hastings78cf85c2014-01-04 12:44:57 -0800271 Add a blank line below the parameters.
272
273 What's a "converter"? It establishes both the type
274 of the variable used in C, and the method to convert the Python
275 value into a C value at runtime.
276 For now you're going to use what's called a "legacy converter"--a
277 convenience syntax intended to make porting old code into Argument
278 Clinic easier.
279
280 For each parameter, copy the "format unit" for that
281 parameter from the ``PyArg_Parse()`` format argument and
282 specify *that* as its converter, as a quoted
283 string. ("format unit" is the formal name for the one-to-three
284 character substring of the ``format`` parameter that tells
285 the argument parsing function what the type of the variable
Larry Hastings6d2ea212014-01-05 02:50:45 -0800286 is and how to convert it. For more on format units please
287 see :ref:`arg-parsing`.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800288
289 For multicharacter format units like ``z#``, use the
290 entire two-or-three character string.
291
292 Sample::
293
Larry Hastings0e254102014-01-26 00:42:02 -0800294 /*[clinic input]
295 module _pickle
296 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
297 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800298
Larry Hastings0e254102014-01-26 00:42:02 -0800299 /*[clinic input]
300 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800301
302 obj: 'O'
303
304 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800305 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800306
3079. If your function has ``|`` in the format string, meaning some
308 parameters have default values, you can ignore it. Argument
309 Clinic infers which parameters are optional based on whether
310 or not they have default values.
311
312 If your function has ``$`` in the format string, meaning it
313 takes keyword-only arguments, specify ``*`` on a line by
314 itself before the first keyword-only argument, indented the
315 same as the parameter lines.
316
Larry Hastings0e254102014-01-26 00:42:02 -0800317 (``_pickle.Pickler.dump`` has neither, so our sample is unchanged.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800318
319
Larry Hastings6d2ea212014-01-05 02:50:45 -080032010. If the existing C function calls :c:func:`PyArg_ParseTuple`
321 (as opposed to :c:func:`PyArg_ParseTupleAndKeywords`), then all its
Larry Hastings78cf85c2014-01-04 12:44:57 -0800322 arguments are positional-only.
323
324 To mark all parameters as positional-only in Argument Clinic,
325 add a ``/`` on a line by itself after the last parameter,
326 indented the same as the parameter lines.
327
Larry Hastings6d2ea212014-01-05 02:50:45 -0800328 Currently this is all-or-nothing; either all parameters are
329 positional-only, or none of them are. (In the future Argument
330 Clinic may relax this restriction.)
331
Larry Hastings78cf85c2014-01-04 12:44:57 -0800332 Sample::
333
Larry Hastings61272b72014-01-07 12:41:53 -0800334 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800335 module _pickle
336 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800337 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800338
Larry Hastings61272b72014-01-07 12:41:53 -0800339 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800340 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800341
342 obj: 'O'
343 /
344
345 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800346 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800347
Larry Hastings6d2ea212014-01-05 02:50:45 -080034811. It's helpful to write a per-parameter docstring for each parameter.
349 But per-parameter docstrings are optional; you can skip this step
350 if you prefer.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800351
Larry Hastings6d2ea212014-01-05 02:50:45 -0800352 Here's how to add a per-parameter docstring. The first line
Larry Hastings78cf85c2014-01-04 12:44:57 -0800353 of the per-parameter docstring must be indented further than the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800354 parameter definition. The left margin of this first line establishes
355 the left margin for the whole per-parameter docstring; all the text
356 you write will be outdented by this amount. You can write as much
357 text as you like, across multiple lines if you wish.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800358
359 Sample::
360
Larry Hastings61272b72014-01-07 12:41:53 -0800361 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800362 module _pickle
363 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800364 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800365
Larry Hastings61272b72014-01-07 12:41:53 -0800366 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800367 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800368
369 obj: 'O'
370 The object to be pickled.
371 /
372
373 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800374 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800375
37612. Save and close the file, then run ``Tools/clinic/clinic.py`` on it.
377 With luck everything worked and your block now has output! Reopen
378 the file in your text editor to see::
379
Larry Hastings61272b72014-01-07 12:41:53 -0800380 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800381 module _pickle
382 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800383 [clinic start generated code]*/
384 /*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800385
Larry Hastings61272b72014-01-07 12:41:53 -0800386 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800387 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800388
389 obj: 'O'
390 The object to be pickled.
391 /
392
393 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800394 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800395
Larry Hastings0e254102014-01-26 00:42:02 -0800396 PyDoc_STRVAR(_pickle_Pickler_dump__doc__,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800397 "Write a pickled representation of obj to the open file.\n"
398 "\n"
399 ...
400 static PyObject *
Larry Hastings0e254102014-01-26 00:42:02 -0800401 _pickle_Pickler_dump_impl(PicklerObject *self, PyObject *obj)
Larry Hastings61272b72014-01-07 12:41:53 -0800402 /*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800403
Larry Hastings6d2ea212014-01-05 02:50:45 -0800404 Obviously, if Argument Clinic didn't produce any output, it's because
405 it found an error in your input. Keep fixing your errors and retrying
406 until Argument Clinic processes your file without complaint.
407
Larry Hastings78cf85c2014-01-04 12:44:57 -080040813. Double-check that the argument-parsing code Argument Clinic generated
409 looks basically the same as the existing code.
410
411 First, ensure both places use the same argument-parsing function.
412 The existing code must call either
Larry Hastings6d2ea212014-01-05 02:50:45 -0800413 :c:func:`PyArg_ParseTuple` or :c:func:`PyArg_ParseTupleAndKeywords`;
Larry Hastings78cf85c2014-01-04 12:44:57 -0800414 ensure that the code generated by Argument Clinic calls the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800415 *exact* same function.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800416
Larry Hastings6d2ea212014-01-05 02:50:45 -0800417 Second, the format string passed in to :c:func:`PyArg_ParseTuple` or
418 :c:func:`PyArg_ParseTupleAndKeywords` should be *exactly* the same
419 as the hand-written one in the existing function, up to the colon
420 or semi-colon.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800421
Larry Hastings6d2ea212014-01-05 02:50:45 -0800422 (Argument Clinic always generates its format strings
423 with a ``:`` followed by the name of the function. If the
424 existing code's format string ends with ``;``, to provide
425 usage help, this change is harmless--don't worry about it.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800426
Larry Hastings6d2ea212014-01-05 02:50:45 -0800427 Third, for parameters whose format units require two arguments
428 (like a length variable, or an encoding string, or a pointer
429 to a conversion function), ensure that the second argument is
430 *exactly* the same between the two invocations.
431
432 Fourth, inside the output portion of the block you'll find a preprocessor
433 macro defining the appropriate static :c:type:`PyMethodDef` structure for
434 this builtin::
435
Larry Hastings0e254102014-01-26 00:42:02 -0800436 #define __PICKLE_PICKLER_DUMP_METHODDEF \
437 {"dump", (PyCFunction)__pickle_Pickler_dump, METH_O, __pickle_Pickler_dump__doc__},
Larry Hastings6d2ea212014-01-05 02:50:45 -0800438
439 This static structure should be *exactly* the same as the existing static
440 :c:type:`PyMethodDef` structure for this builtin.
441
442 If any of these items differ in *any way*,
443 adjust your Argument Clinic function specification and rerun
444 ``Tools/clinic/clinic.py`` until they *are* the same.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800445
446
44714. Notice that the last line of its output is the declaration
448 of your "impl" function. This is where the builtin's implementation goes.
449 Delete the existing prototype of the function you're modifying, but leave
450 the opening curly brace. Now delete its argument parsing code and the
451 declarations of all the variables it dumps the arguments into.
452 Notice how the Python arguments are now arguments to this impl function;
453 if the implementation used different names for these variables, fix it.
Larry Hastings6d2ea212014-01-05 02:50:45 -0800454
455 Let's reiterate, just because it's kind of weird. Your code should now
456 look like this::
457
458 static return_type
459 your_function_impl(...)
Larry Hastings61272b72014-01-07 12:41:53 -0800460 /*[clinic end generated code: checksum=...]*/
Larry Hastings6d2ea212014-01-05 02:50:45 -0800461 {
462 ...
463
464 Argument Clinic generated the checksum line and the function prototype just
465 above it. You should write the opening (and closing) curly braces for the
466 function, and the implementation inside.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800467
468 Sample::
469
Larry Hastings61272b72014-01-07 12:41:53 -0800470 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800471 module _pickle
472 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800473 [clinic start generated code]*/
474 /*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800475
Larry Hastings61272b72014-01-07 12:41:53 -0800476 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800477 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800478
479 obj: 'O'
480 The object to be pickled.
481 /
482
483 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800484 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800485
Larry Hastings0e254102014-01-26 00:42:02 -0800486 PyDoc_STRVAR(__pickle_Pickler_dump__doc__,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800487 "Write a pickled representation of obj to the open file.\n"
488 "\n"
489 ...
490 static PyObject *
Larry Hastings0e254102014-01-26 00:42:02 -0800491 _pickle_Pickler_dump_impl(PicklerObject *self, PyObject *obj)
Larry Hastings61272b72014-01-07 12:41:53 -0800492 /*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800493 {
494 /* Check whether the Pickler was initialized correctly (issue3664).
495 Developers often forget to call __init__() in their subclasses, which
496 would trigger a segfault without this check. */
497 if (self->write == NULL) {
498 PyErr_Format(PicklingError,
499 "Pickler.__init__() was not called by %s.__init__()",
500 Py_TYPE(self)->tp_name);
501 return NULL;
502 }
503
504 if (_Pickler_ClearBuffer(self) < 0)
505 return NULL;
506
507 ...
508
Larry Hastings6d2ea212014-01-05 02:50:45 -080050915. Remember the macro with the :c:type:`PyMethodDef` structure for this
510 function? Find the existing :c:type:`PyMethodDef` structure for this
511 function and replace it with a reference to the macro. (If the builtin
512 is at module scope, this will probably be very near the end of the file;
513 if the builtin is a class method, this will probably be below but relatively
514 near to the implementation.)
515
516 Note that the body of the macro contains a trailing comma. So when you
517 replace the existing static :c:type:`PyMethodDef` structure with the macro,
518 *don't* add a comma to the end.
519
520 Sample::
521
522 static struct PyMethodDef Pickler_methods[] = {
Larry Hastings0e254102014-01-26 00:42:02 -0800523 __PICKLE_PICKLER_DUMP_METHODDEF
524 __PICKLE_PICKLER_CLEAR_MEMO_METHODDEF
Larry Hastings6d2ea212014-01-05 02:50:45 -0800525 {NULL, NULL} /* sentinel */
526 };
527
528
52916. Compile, then run the relevant portions of the regression-test suite.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800530 This change should not introduce any new compile-time warnings or errors,
531 and there should be no externally-visible change to Python's behavior.
532
533 Well, except for one difference: ``inspect.signature()`` run on your function
534 should now provide a valid signature!
535
536 Congratulations, you've ported your first function to work with Argument Clinic!
537
Larry Hastings78cf85c2014-01-04 12:44:57 -0800538Advanced Topics
539===============
540
Larry Hastings4a55fc52014-01-12 11:09:57 -0800541Now that you've had some experience working with Argument Clinic, it's time
542for some advanced topics.
543
544
545Symbolic default values
546-----------------------
547
548The default value you provide for a parameter can't be any arbitrary
549expression. Currently the following are explicitly supported:
550
551* Numeric constants (integer and float)
552* String constants
553* ``True``, ``False``, and ``None``
554* Simple symbolic constants like ``sys.maxsize``, which must
555 start with the name of the module
556
557In case you're curious, this is implemented in ``from_builtin()``
558in ``Lib/inspect.py``.
559
560(In the future, this may need to get even more elaborate,
561to allow full expressions like ``CONSTANT - 1``.)
562
Larry Hastings78cf85c2014-01-04 12:44:57 -0800563
Larry Hastings7726ac92014-01-31 22:03:12 -0800564Renaming the C functions and variables generated by Argument Clinic
565-------------------------------------------------------------------
Larry Hastings78cf85c2014-01-04 12:44:57 -0800566
567Argument Clinic automatically names the functions it generates for you.
568Occasionally this may cause a problem, if the generated name collides with
Larry Hastings6d2ea212014-01-05 02:50:45 -0800569the name of an existing C function. There's an easy solution: override the names
570used for the C functions. Just add the keyword ``"as"``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800571to your function declaration line, followed by the function name you wish to use.
Larry Hastings6d2ea212014-01-05 02:50:45 -0800572Argument Clinic will use that function name for the base (generated) function,
573then add ``"_impl"`` to the end and use that for the name of the impl function.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800574
575For example, if we wanted to rename the C function names generated for
576``pickle.Pickler.dump``, it'd look like this::
577
Larry Hastings61272b72014-01-07 12:41:53 -0800578 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800579 pickle.Pickler.dump as pickler_dumper
580
581 ...
582
583The base function would now be named ``pickler_dumper()``,
Larry Hastings6d2ea212014-01-05 02:50:45 -0800584and the impl function would now be named ``pickler_dumper_impl()``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800585
586
Larry Hastings7726ac92014-01-31 22:03:12 -0800587Similarly, you may have a problem where you want to give a parameter
588a specific Python name, but that name may be inconvenient in C. Argument
589Clinic allows you to give a parameter different names in Python and in C,
590using the same ``"as"`` syntax::
591
592 /*[clinic input]
593 pickle.Pickler.dump
594
595 obj: object
596 file as file_obj: object
597 protocol: object = NULL
598 *
599 fix_imports: bool = True
600
601Here, the name used in Python (in the signature and the ``keywords``
602array) would be ``file``, but the C variable would be named ``file_obj``.
603
604You can use this to rename the ``self`` parameter too!
605
Larry Hastings4a55fc52014-01-12 11:09:57 -0800606
607Converting functions using PyArg_UnpackTuple
608--------------------------------------------
609
610To convert a function parsing its arguments with :c:func:`PyArg_UnpackTuple`,
611simply write out all the arguments, specifying each as an ``object``. You
612may specify the ``type`` argument to cast the type as appropriate. All
613arguments should be marked positional-only (add a ``/`` on a line by itself
614after the last argument).
615
616Currently the generated code will use :c:func:`PyArg_ParseTuple`, but this
617will change soon.
618
Larry Hastings78cf85c2014-01-04 12:44:57 -0800619Optional Groups
620---------------
621
622Some legacy functions have a tricky approach to parsing their arguments:
623they count the number of positional arguments, then use a ``switch`` statement
Larry Hastings6d2ea212014-01-05 02:50:45 -0800624to call one of several different :c:func:`PyArg_ParseTuple` calls depending on
Larry Hastings78cf85c2014-01-04 12:44:57 -0800625how many positional arguments there are. (These functions cannot accept
626keyword-only arguments.) This approach was used to simulate optional
Larry Hastings6d2ea212014-01-05 02:50:45 -0800627arguments back before :c:func:`PyArg_ParseTupleAndKeywords` was created.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800628
Larry Hastings6d2ea212014-01-05 02:50:45 -0800629While functions using this approach can often be converted to
630use :c:func:`PyArg_ParseTupleAndKeywords`, optional arguments, and default values,
631it's not always possible. Some of these legacy functions have
632behaviors :c:func:`PyArg_ParseTupleAndKeywords` doesn't directly support.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800633The most obvious example is the builtin function ``range()``, which has
634an optional argument on the *left* side of its required argument!
635Another example is ``curses.window.addch()``, which has a group of two
636arguments that must always be specified together. (The arguments are
637called ``x`` and ``y``; if you call the function passing in ``x``,
638you must also pass in ``y``--and if you don't pass in ``x`` you may not
639pass in ``y`` either.)
640
Larry Hastings6d2ea212014-01-05 02:50:45 -0800641In any case, the goal of Argument Clinic is to support argument parsing
642for all existing CPython builtins without changing their semantics.
643Therefore Argument Clinic supports
644this alternate approach to parsing, using what are called *optional groups*.
645Optional groups are groups of arguments that must all be passed in together.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800646They can be to the left or the right of the required arguments. They
647can *only* be used with positional-only parameters.
648
Larry Hastings42d9e1b2014-01-22 05:49:11 -0800649.. note:: Optional groups are *only* intended for use when converting
650 functions that make multiple calls to :c:func:`PyArg_ParseTuple`!
651 Functions that use *any* other approach for parsing arguments
652 should *almost never* be converted to Argument Clinic using
653 optional groups. Functions using optional groups currently
654 cannot have accurate sigantures in Python, because Python just
655 doesn't understand the concept. Please avoid using optional
656 groups wherever possible.
657
Larry Hastings78cf85c2014-01-04 12:44:57 -0800658To specify an optional group, add a ``[`` on a line by itself before
Larry Hastings6d2ea212014-01-05 02:50:45 -0800659the parameters you wish to group together, and a ``]`` on a line by itself
660after these parameters. As an example, here's how ``curses.window.addch``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800661uses optional groups to make the first two parameters and the last
662parameter optional::
663
Larry Hastings61272b72014-01-07 12:41:53 -0800664 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800665
666 curses.window.addch
667
668 [
669 x: int
670 X-coordinate.
671 y: int
672 Y-coordinate.
673 ]
674
675 ch: object
676 Character to add.
677
678 [
679 attr: long
680 Attributes for the character.
681 ]
682 /
683
684 ...
685
686
687Notes:
688
689* For every optional group, one additional parameter will be passed into the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800690 impl function representing the group. The parameter will be an int named
691 ``group_{direction}_{number}``,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800692 where ``{direction}`` is either ``right`` or ``left`` depending on whether the group
693 is before or after the required parameters, and ``{number}`` is a monotonically
694 increasing number (starting at 1) indicating how far away the group is from
695 the required parameters. When the impl is called, this parameter will be set
696 to zero if this group was unused, and set to non-zero if this group was used.
697 (By used or unused, I mean whether or not the parameters received arguments
698 in this invocation.)
699
700* If there are no required arguments, the optional groups will behave
Larry Hastings6d2ea212014-01-05 02:50:45 -0800701 as if they're to the right of the required arguments.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800702
703* In the case of ambiguity, the argument parsing code
704 favors parameters on the left (before the required parameters).
705
Larry Hastings6d2ea212014-01-05 02:50:45 -0800706* Optional groups can only contain positional-only parameters.
707
Larry Hastings78cf85c2014-01-04 12:44:57 -0800708* Optional groups are *only* intended for legacy code. Please do not
709 use optional groups for new code.
710
711
712Using real Argument Clinic converters, instead of "legacy converters"
713---------------------------------------------------------------------
714
715To save time, and to minimize how much you need to learn
716to achieve your first port to Argument Clinic, the walkthrough above tells
Larry Hastings6d2ea212014-01-05 02:50:45 -0800717you to use "legacy converters". "Legacy converters" are a convenience,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800718designed explicitly to make porting existing code to Argument Clinic
Larry Hastings4a55fc52014-01-12 11:09:57 -0800719easier. And to be clear, their use is acceptable when porting code for
720Python 3.4.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800721
722However, in the long term we probably want all our blocks to
723use Argument Clinic's real syntax for converters. Why? A couple
724reasons:
725
726* The proper converters are far easier to read and clearer in their intent.
727* There are some format units that are unsupported as "legacy converters",
728 because they require arguments, and the legacy converter syntax doesn't
729 support specifying arguments.
730* In the future we may have a new argument parsing library that isn't
Larry Hastings6d2ea212014-01-05 02:50:45 -0800731 restricted to what :c:func:`PyArg_ParseTuple` supports; this flexibility
732 won't be available to parameters using legacy converters.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800733
Larry Hastings4a55fc52014-01-12 11:09:57 -0800734Therefore, if you don't mind a little extra effort, please use the normal
735converters instead of legacy converters.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800736
737In a nutshell, the syntax for Argument Clinic (non-legacy) converters
738looks like a Python function call. However, if there are no explicit
739arguments to the function (all functions take their default values),
740you may omit the parentheses. Thus ``bool`` and ``bool()`` are exactly
Larry Hastings6d2ea212014-01-05 02:50:45 -0800741the same converters.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800742
Larry Hastings6d2ea212014-01-05 02:50:45 -0800743All arguments to Argument Clinic converters are keyword-only.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800744All Argument Clinic converters accept the following arguments:
745
Larry Hastings2a727912014-01-16 11:32:01 -0800746 ``c_default``
747 The default value for this parameter when defined in C.
748 Specifically, this will be the initializer for the variable declared
749 in the "parse function". See :ref:`the section on default values <default_values>`
750 for how to use this.
751 Specified as a string.
Larry Hastings4a55fc52014-01-12 11:09:57 -0800752
Larry Hastings2a727912014-01-16 11:32:01 -0800753 ``annotation``
754 The annotation value for this parameter. Not currently supported,
755 because PEP 8 mandates that the Python library may not use
756 annotations.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800757
Larry Hastings2a727912014-01-16 11:32:01 -0800758In addition, some converters accept additional arguments. Here is a list
759of these arguments, along with their meanings:
Larry Hastings78cf85c2014-01-04 12:44:57 -0800760
Larry Hastings2a727912014-01-16 11:32:01 -0800761 ``bitwise``
762 Only supported for unsigned integers. The native integer value of this
763 Python argument will be written to the parameter without any range checking,
764 even for negative values.
Larry Hastings4a55fc52014-01-12 11:09:57 -0800765
Larry Hastings2a727912014-01-16 11:32:01 -0800766 ``converter``
767 Only supported by the ``object`` converter. Specifies the name of a
768 :ref:`C "converter function" <o_ampersand>`
769 to use to convert this object to a native type.
770
771 ``encoding``
772 Only supported for strings. Specifies the encoding to use when converting
773 this string from a Python str (Unicode) value into a C ``char *`` value.
774
775 ``length``
776 Only supported for strings. If true, requests that the length of the
777 string be passed in to the impl function, just after the string parameter,
778 in a parameter named ``<parameter_name>_length``.
779
780 ``nullable``
781 Only supported for strings. If true, this parameter may also be set to
782 ``None``, in which case the C parameter will be set to ``NULL``.
783
784 ``subclass_of``
785 Only supported for the ``object`` converter. Requires that the Python
786 value be a subclass of a Python type, as expressed in C.
787
788 ``types``
789 Only supported for the ``object`` (and ``self``) converter. Specifies
790 the C type that will be used to declare the variable. Default value is
791 ``"PyObject *"``.
792
793 ``types``
794 A string containing a list of Python types (and possibly pseudo-types);
795 this restricts the allowable Python argument to values of these types.
796 (This is not a general-purpose facility; as a rule it only supports
797 specific lists of types as shown in the legacy converter table.)
798
799 ``zeroes``
800 Only supported for strings. If true, embedded NUL bytes (``'\\0'``) are
801 permitted inside the value.
802
803Please note, not every possible combination of arguments will work.
804Often these arguments are implemented internally by specific ``PyArg_ParseTuple``
805*format units*, with specific behavior. For example, currently you cannot
806call ``str`` and pass in ``zeroes=True`` without also specifying an ``encoding``;
807although it's perfectly reasonable to think this would work, these semantics don't
808map to any existing format unit. So Argument Clinic doesn't support it. (Or, at
809least, not yet.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800810
811Below is a table showing the mapping of legacy converters into real
812Argument Clinic converters. On the left is the legacy converter,
813on the right is the text you'd replace it with.
814
815========= =================================================================================
Larry Hastingsb7ccb202014-01-18 23:50:21 -0800816``'B'`` ``unsigned_char(bitwise=True)``
817``'b'`` ``unsigned_char``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800818``'c'`` ``char``
819``'C'`` ``int(types='str')``
820``'d'`` ``double``
821``'D'`` ``Py_complex``
822``'es#'`` ``str(encoding='name_of_encoding', length=True, zeroes=True)``
823``'es'`` ``str(encoding='name_of_encoding')``
824``'et#'`` ``str(encoding='name_of_encoding', types='bytes bytearray str', length=True)``
825``'et'`` ``str(encoding='name_of_encoding', types='bytes bytearray str')``
826``'f'`` ``float``
827``'h'`` ``short``
Larry Hastings4a55fc52014-01-12 11:09:57 -0800828``'H'`` ``unsigned_short(bitwise=True)``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800829``'i'`` ``int``
Larry Hastings4a55fc52014-01-12 11:09:57 -0800830``'I'`` ``unsigned_int(bitwise=True)``
831``'k'`` ``unsigned_long(bitwise=True)``
832``'K'`` ``unsigned_PY_LONG_LONG(bitwise=True)``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800833``'L'`` ``PY_LONG_LONG``
834``'n'`` ``Py_ssize_t``
Larry Hastings77561cc2014-01-07 12:13:13 -0800835``'O!'`` ``object(subclass_of='&PySomething_Type')``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800836``'O&'`` ``object(converter='name_of_c_function')``
837``'O'`` ``object``
838``'p'`` ``bool``
839``'s#'`` ``str(length=True)``
840``'S'`` ``PyBytesObject``
841``'s'`` ``str``
842``'s*'`` ``Py_buffer(types='str bytes bytearray buffer')``
843``'u#'`` ``Py_UNICODE(length=True)``
844``'u'`` ``Py_UNICODE``
845``'U'`` ``unicode``
846``'w*'`` ``Py_buffer(types='bytearray rwbuffer')``
Larry Hastings2a727912014-01-16 11:32:01 -0800847``'y#'`` ``str(types='bytes', length=True)``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800848``'Y'`` ``PyByteArrayObject``
Larry Hastings2a727912014-01-16 11:32:01 -0800849``'y'`` ``str(types='bytes')``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800850``'y*'`` ``Py_buffer``
851``'Z#'`` ``Py_UNICODE(nullable=True, length=True)``
852``'z#'`` ``str(nullable=True, length=True)``
853``'Z'`` ``Py_UNICODE(nullable=True)``
854``'z'`` ``str(nullable=True)``
855``'z*'`` ``Py_buffer(types='str bytes bytearray buffer', nullable=True)``
856========= =================================================================================
857
858As an example, here's our sample ``pickle.Pickler.dump`` using the proper
859converter::
860
Larry Hastings61272b72014-01-07 12:41:53 -0800861 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800862 pickle.Pickler.dump
863
864 obj: object
865 The object to be pickled.
866 /
867
868 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800869 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800870
871Argument Clinic will show you all the converters it has
872available. For each converter it'll show you all the parameters
873it accepts, along with the default value for each parameter.
874Just run ``Tools/clinic/clinic.py --converters`` to see the full list.
875
Larry Hastings4a55fc52014-01-12 11:09:57 -0800876Py_buffer
877---------
878
879When using the ``Py_buffer`` converter
Larry Hastings0191be32014-01-12 13:57:36 -0800880(or the ``'s*'``, ``'w*'``, ``'*y'``, or ``'z*'`` legacy converters),
881you *must* not call :c:func:`PyBuffer_Release` on the provided buffer.
882Argument Clinic generates code that does it for you (in the parsing function).
883
Larry Hastings4a55fc52014-01-12 11:09:57 -0800884
Larry Hastings78cf85c2014-01-04 12:44:57 -0800885
886Advanced converters
887-------------------
888
Senthil Kumaranb4760ef2015-06-14 17:35:37 -0700889Remember those format units you skipped for your first
Larry Hastings78cf85c2014-01-04 12:44:57 -0800890time because they were advanced? Here's how to handle those too.
891
892The trick is, all those format units take arguments--either
893conversion functions, or types, or strings specifying an encoding.
894(But "legacy converters" don't support arguments. That's why we
895skipped them for your first function.) The argument you specified
896to the format unit is now an argument to the converter; this
Larry Hastings77561cc2014-01-07 12:13:13 -0800897argument is either ``converter`` (for ``O&``), ``subclass_of`` (for ``O!``),
Larry Hastings78cf85c2014-01-04 12:44:57 -0800898or ``encoding`` (for all the format units that start with ``e``).
899
Larry Hastings77561cc2014-01-07 12:13:13 -0800900When using ``subclass_of``, you may also want to use the other
901custom argument for ``object()``: ``type``, which lets you set the type
902actually used for the parameter. For example, if you want to ensure
903that the object is a subclass of ``PyUnicode_Type``, you probably want
904to use the converter ``object(type='PyUnicodeObject *', subclass_of='&PyUnicode_Type')``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800905
Larry Hastings77561cc2014-01-07 12:13:13 -0800906One possible problem with using Argument Clinic: it takes away some possible
907flexibility for the format units starting with ``e``. When writing a
908``PyArg_Parse`` call by hand, you could theoretically decide at runtime what
Larry Hastings6d2ea212014-01-05 02:50:45 -0800909encoding string to pass in to :c:func:`PyArg_ParseTuple`. But now this string must
Larry Hastings77561cc2014-01-07 12:13:13 -0800910be hard-coded at Argument-Clinic-preprocessing-time. This limitation is deliberate;
911it made supporting this format unit much easier, and may allow for future optimizations.
912This restriction doesn't seem unreasonable; CPython itself always passes in static
Larry Hastings6d2ea212014-01-05 02:50:45 -0800913hard-coded encoding strings for parameters whose format units start with ``e``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800914
915
Larry Hastings2a727912014-01-16 11:32:01 -0800916.. _default_values:
917
918Parameter default values
919------------------------
920
921Default values for parameters can be any of a number of values.
922At their simplest, they can be string, int, or float literals::
923
924 foo: str = "abc"
925 bar: int = 123
926 bat: float = 45.6
927
928They can also use any of Python's built-in constants::
929
930 yep: bool = True
931 nope: bool = False
932 nada: object = None
933
934There's also special support for a default value of ``NULL``, and
935for simple expressions, documented in the following sections.
936
937
938The ``NULL`` default value
939--------------------------
940
941For string and object parameters, you can set them to ``None`` to indicate
942that there's no default. However, that means the C variable will be
943initialized to ``Py_None``. For convenience's sakes, there's a special
944value called ``NULL`` for just this reason: from Python's perspective it
945behaves like a default value of ``None``, but the C variable is initialized
946with ``NULL``.
947
948Expressions specified as default values
949---------------------------------------
950
951The default value for a parameter can be more than just a literal value.
952It can be an entire expression, using math operators and looking up attributes
953on objects. However, this support isn't exactly simple, because of some
954non-obvious semantics.
955
956Consider the following example::
957
958 foo: Py_ssize_t = sys.maxsize - 1
959
960``sys.maxsize`` can have different values on different platforms. Therefore
961Argument Clinic can't simply evaluate that expression locally and hard-code it
962in C. So it stores the default in such a way that it will get evaluated at
963runtime, when the user asks for the function's signature.
964
965What namespace is available when the expression is evaluated? It's evaluated
966in the context of the module the builtin came from. So, if your module has an
967attribute called "``max_widgets``", you may simply use it::
968
969 foo: Py_ssize_t = max_widgets
970
971If the symbol isn't found in the current module, it fails over to looking in
972``sys.modules``. That's how it can find ``sys.maxsize`` for example. (Since you
973don't know in advance what modules the user will load into their interpreter,
974it's best to restrict yourself to modules that are preloaded by Python itself.)
975
976Evaluating default values only at runtime means Argument Clinic can't compute
977the correct equivalent C default value. So you need to tell it explicitly.
978When you use an expression, you must also specify the equivalent expression
979in C, using the ``c_default`` parameter to the converter::
980
981 foo: Py_ssize_t(c_default="PY_SSIZE_T_MAX - 1") = sys.maxsize - 1
982
983Another complication: Argument Clinic can't know in advance whether or not the
984expression you supply is valid. It parses it to make sure it looks legal, but
985it can't *actually* know. You must be very careful when using expressions to
986specify values that are guaranteed to be valid at runtime!
987
988Finally, because expressions must be representable as static C values, there
989are many restrictions on legal expressions. Here's a list of Python features
990you're not permitted to use:
991
992* Function calls.
993* Inline if statements (``3 if foo else 5``).
994* Automatic sequence unpacking (``*[1, 2, 3]``).
995* List/set/dict comprehensions and generator expressions.
996* Tuple/list/set/dict literals.
997
998
999
Larry Hastings78cf85c2014-01-04 12:44:57 -08001000Using a return converter
1001------------------------
1002
1003By default the impl function Argument Clinic generates for you returns ``PyObject *``.
1004But your C function often computes some C type, then converts it into the ``PyObject *``
1005at the last moment. Argument Clinic handles converting your inputs from Python types
1006into native C types--why not have it convert your return value from a native C type
1007into a Python type too?
1008
1009That's what a "return converter" does. It changes your impl function to return
1010some C type, then adds code to the generated (non-impl) function to handle converting
1011that value into the appropriate ``PyObject *``.
1012
1013The syntax for return converters is similar to that of parameter converters.
1014You specify the return converter like it was a return annotation on the
1015function itself. Return converters behave much the same as parameter converters;
1016they take arguments, the arguments are all keyword-only, and if you're not changing
1017any of the default arguments you can omit the parentheses.
1018
1019(If you use both ``"as"`` *and* a return converter for your function,
1020the ``"as"`` should come before the return converter.)
1021
1022There's one additional complication when using return converters: how do you
Senthil Kumaranb4760ef2015-06-14 17:35:37 -07001023indicate an error has occurred? Normally, a function returns a valid (non-``NULL``)
Larry Hastings78cf85c2014-01-04 12:44:57 -08001024pointer for success, and ``NULL`` for failure. But if you use an integer return converter,
1025all integers are valid. How can Argument Clinic detect an error? Its solution: each return
1026converter implicitly looks for a special value that indicates an error. If you return
1027that value, and an error has been set (``PyErr_Occurred()`` returns a true
Senthil Kumaranb4760ef2015-06-14 17:35:37 -07001028value), then the generated code will propagate the error. Otherwise it will
Larry Hastings78cf85c2014-01-04 12:44:57 -08001029encode the value you return like normal.
1030
1031Currently Argument Clinic supports only a few return converters::
1032
Larry Hastings4a55fc52014-01-12 11:09:57 -08001033 bool
Larry Hastings78cf85c2014-01-04 12:44:57 -08001034 int
Larry Hastings4a55fc52014-01-12 11:09:57 -08001035 unsigned int
Larry Hastings78cf85c2014-01-04 12:44:57 -08001036 long
Larry Hastings4a55fc52014-01-12 11:09:57 -08001037 unsigned int
1038 size_t
Larry Hastings78cf85c2014-01-04 12:44:57 -08001039 Py_ssize_t
Larry Hastings4a55fc52014-01-12 11:09:57 -08001040 float
1041 double
Larry Hastings78cf85c2014-01-04 12:44:57 -08001042 DecodeFSDefault
1043
1044None of these take parameters. For the first three, return -1 to indicate
1045error. For ``DecodeFSDefault``, the return type is ``char *``; return a NULL
1046pointer to indicate an error.
1047
Larry Hastings4a55fc52014-01-12 11:09:57 -08001048(There's also an experimental ``NoneType`` converter, which lets you
1049return ``Py_None`` on success or ``NULL`` on failure, without having
1050to increment the reference count on ``Py_None``. I'm not sure it adds
1051enough clarity to be worth using.)
1052
Larry Hastings6d2ea212014-01-05 02:50:45 -08001053To see all the return converters Argument Clinic supports, along with
1054their parameters (if any),
1055just run ``Tools/clinic/clinic.py --converters`` for the full list.
1056
1057
Larry Hastings4a714d42014-01-14 22:22:41 -08001058Cloning existing functions
1059--------------------------
1060
1061If you have a number of functions that look similar, you may be able to
1062use Clinic's "clone" feature. When you clone an existing function,
1063you reuse:
1064
1065* its parameters, including
1066
1067 * their names,
1068
1069 * their converters, with all parameters,
1070
1071 * their default values,
1072
1073 * their per-parameter docstrings,
1074
1075 * their *kind* (whether they're positional only,
1076 positional or keyword, or keyword only), and
1077
1078* its return converter.
1079
1080The only thing not copied from the original function is its docstring;
1081the syntax allows you to specify a new docstring.
1082
1083Here's the syntax for cloning a function::
1084
1085 /*[clinic input]
1086 module.class.new_function [as c_basename] = module.class.existing_function
1087
1088 Docstring for new_function goes here.
1089 [clinic start generated code]*/
1090
1091(The functions can be in different modules or classes. I wrote
1092``module.class`` in the sample just to illustrate that you must
1093use the full path to *both* functions.)
1094
1095Sorry, there's no syntax for partially-cloning a function, or cloning a function
1096then modifying it. Cloning is an all-or nothing proposition.
1097
1098Also, the function you are cloning from must have been previously defined
1099in the current file.
1100
Larry Hastings78cf85c2014-01-04 12:44:57 -08001101Calling Python code
1102-------------------
1103
1104The rest of the advanced topics require you to write Python code
Larry Hastings6d2ea212014-01-05 02:50:45 -08001105which lives inside your C file and modifies Argument Clinic's
1106runtime state. This is simple: you simply define a Python block.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001107
1108A Python block uses different delimiter lines than an Argument
1109Clinic function block. It looks like this::
1110
Larry Hastings61272b72014-01-07 12:41:53 -08001111 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001112 # python code goes here
Larry Hastings61272b72014-01-07 12:41:53 -08001113 [python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001114
1115All the code inside the Python block is executed at the
1116time it's parsed. All text written to stdout inside the block
1117is redirected into the "output" after the block.
1118
1119As an example, here's a Python block that adds a static integer
1120variable to the C code::
1121
Larry Hastings61272b72014-01-07 12:41:53 -08001122 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001123 print('static int __ignored_unused_variable__ = 0;')
Larry Hastings61272b72014-01-07 12:41:53 -08001124 [python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001125 static int __ignored_unused_variable__ = 0;
1126 /*[python checksum:...]*/
1127
1128
1129Using a "self converter"
1130------------------------
1131
1132Argument Clinic automatically adds a "self" parameter for you
Larry Hastings0e254102014-01-26 00:42:02 -08001133using a default converter. It automatically sets the ``type``
1134of this parameter to the "pointer to an instance" you specified
1135when you declared the type. However, you can override
Larry Hastings78cf85c2014-01-04 12:44:57 -08001136Argument Clinic's converter and specify one yourself.
1137Just add your own ``self`` parameter as the first parameter in a
1138block, and ensure that its converter is an instance of
1139``self_converter`` or a subclass thereof.
1140
Larry Hastings0e254102014-01-26 00:42:02 -08001141What's the point? This lets you override the type of ``self``,
1142or give it a different default name.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001143
1144How do you specify the custom type you want to cast ``self`` to?
1145If you only have one or two functions with the same type for ``self``,
1146you can directly use Argument Clinic's existing ``self`` converter,
1147passing in the type you want to use as the ``type`` parameter::
1148
Larry Hastings61272b72014-01-07 12:41:53 -08001149 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001150
1151 _pickle.Pickler.dump
1152
1153 self: self(type="PicklerObject *")
1154 obj: object
1155 /
1156
1157 Write a pickled representation of the given object to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -08001158 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001159
1160On the other hand, if you have a lot of functions that will use the same
1161type for ``self``, it's best to create your own converter, subclassing
1162``self_converter`` but overwriting the ``type`` member::
1163
Zachary Warec1cb2272014-01-09 21:41:23 -06001164 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001165 class PicklerObject_converter(self_converter):
1166 type = "PicklerObject *"
Zachary Warec1cb2272014-01-09 21:41:23 -06001167 [python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001168
Larry Hastings61272b72014-01-07 12:41:53 -08001169 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001170
1171 _pickle.Pickler.dump
1172
1173 self: PicklerObject
1174 obj: object
1175 /
1176
1177 Write a pickled representation of the given object to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -08001178 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001179
1180
1181
1182Writing a custom converter
1183--------------------------
1184
1185As we hinted at in the previous section... you can write your own converters!
1186A converter is simply a Python class that inherits from ``CConverter``.
1187The main purpose of a custom converter is if you have a parameter using
1188the ``O&`` format unit--parsing this parameter means calling
Larry Hastings6d2ea212014-01-05 02:50:45 -08001189a :c:func:`PyArg_ParseTuple` "converter function".
Larry Hastings78cf85c2014-01-04 12:44:57 -08001190
1191Your converter class should be named ``*something*_converter``.
1192If the name follows this convention, then your converter class
1193will be automatically registered with Argument Clinic; its name
1194will be the name of your class with the ``_converter`` suffix
Larry Hastings6d2ea212014-01-05 02:50:45 -08001195stripped off. (This is accomplished with a metaclass.)
Larry Hastings78cf85c2014-01-04 12:44:57 -08001196
1197You shouldn't subclass ``CConverter.__init__``. Instead, you should
1198write a ``converter_init()`` function. ``converter_init()``
1199always accepts a ``self`` parameter; after that, all additional
1200parameters *must* be keyword-only. Any arguments passed in to
1201the converter in Argument Clinic will be passed along to your
1202``converter_init()``.
1203
1204There are some additional members of ``CConverter`` you may wish
1205to specify in your subclass. Here's the current list:
1206
1207``type``
1208 The C type to use for this variable.
1209 ``type`` should be a Python string specifying the type, e.g. ``int``.
1210 If this is a pointer type, the type string should end with ``' *'``.
1211
1212``default``
1213 The Python default value for this parameter, as a Python value.
1214 Or the magic value ``unspecified`` if there is no default.
1215
Larry Hastings78cf85c2014-01-04 12:44:57 -08001216``py_default``
1217 ``default`` as it should appear in Python code,
1218 as a string.
1219 Or ``None`` if there is no default.
1220
1221``c_default``
1222 ``default`` as it should appear in C code,
1223 as a string.
1224 Or ``None`` if there is no default.
1225
1226``c_ignored_default``
1227 The default value used to initialize the C variable when
1228 there is no default, but not specifying a default may
Larry Hastings6d2ea212014-01-05 02:50:45 -08001229 result in an "uninitialized variable" warning. This can
Larry Hastings78cf85c2014-01-04 12:44:57 -08001230 easily happen when using option groups--although
Larry Hastings6d2ea212014-01-05 02:50:45 -08001231 properly-written code will never actually use this value,
1232 the variable does get passed in to the impl, and the
1233 C compiler will complain about the "use" of the
1234 uninitialized value. This value should always be a
1235 non-empty string.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001236
1237``converter``
1238 The name of the C converter function, as a string.
1239
1240``impl_by_reference``
1241 A boolean value. If true,
1242 Argument Clinic will add a ``&`` in front of the name of
1243 the variable when passing it into the impl function.
1244
1245``parse_by_reference``
1246 A boolean value. If true,
1247 Argument Clinic will add a ``&`` in front of the name of
Larry Hastings6d2ea212014-01-05 02:50:45 -08001248 the variable when passing it into :c:func:`PyArg_ParseTuple`.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001249
1250
1251Here's the simplest example of a custom converter, from ``Modules/zlibmodule.c``::
1252
Larry Hastings61272b72014-01-07 12:41:53 -08001253 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001254
1255 class uint_converter(CConverter):
1256 type = 'unsigned int'
1257 converter = 'uint_converter'
1258
Larry Hastings61272b72014-01-07 12:41:53 -08001259 [python start generated code]*/
1260 /*[python end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001261
Larry Hastings6d2ea212014-01-05 02:50:45 -08001262This block adds a converter to Argument Clinic named ``uint``. Parameters
Larry Hastings78cf85c2014-01-04 12:44:57 -08001263declared as ``uint`` will be declared as type ``unsigned int``, and will
Larry Hastings6d2ea212014-01-05 02:50:45 -08001264be parsed by the ``'O&'`` format unit, which will call the ``uint_converter``
1265converter function.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001266``uint`` variables automatically support default values.
1267
1268More sophisticated custom converters can insert custom C code to
1269handle initialization and cleanup.
1270You can see more examples of custom converters in the CPython
1271source tree; grep the C files for the string ``CConverter``.
1272
1273Writing a custom return converter
1274---------------------------------
1275
1276Writing a custom return converter is much like writing
Larry Hastings6d2ea212014-01-05 02:50:45 -08001277a custom converter. Except it's somewhat simpler, because return
Larry Hastings78cf85c2014-01-04 12:44:57 -08001278converters are themselves much simpler.
1279
1280Return converters must subclass ``CReturnConverter``.
1281There are no examples yet of custom return converters,
1282because they are not widely used yet. If you wish to
1283write your own return converter, please read ``Tools/clinic/clinic.py``,
1284specifically the implementation of ``CReturnConverter`` and
1285all its subclasses.
1286
Larry Hastings4a55fc52014-01-12 11:09:57 -08001287METH_O and METH_NOARGS
1288----------------------------------------------
1289
1290To convert a function using ``METH_O``, make sure the function's
1291single argument is using the ``object`` converter, and mark the
1292arguments as positional-only::
1293
1294 /*[clinic input]
1295 meth_o_sample
1296
1297 argument: object
1298 /
1299 [clinic start generated code]*/
1300
1301
1302To convert a function using ``METH_NOARGS``, just don't specify
1303any arguments.
1304
1305You can still use a self converter, a return converter, and specify
1306a ``type`` argument to the object converter for ``METH_O``.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001307
Larry Hastingsb7ccb202014-01-18 23:50:21 -08001308tp_new and tp_init functions
1309----------------------------------------------
1310
Larry Hastings42d9e1b2014-01-22 05:49:11 -08001311You can convert ``tp_new`` and ``tp_init`` functions. Just name
1312them ``__new__`` or ``__init__`` as appropriate. Notes:
Larry Hastingsb7ccb202014-01-18 23:50:21 -08001313
1314* The function name generated for ``__new__`` doesn't end in ``__new__``
1315 like it would by default. It's just the name of the class, converted
1316 into a valid C identifier.
1317
1318* No ``PyMethodDef`` ``#define`` is generated for these functions.
1319
1320* ``__init__`` functions return ``int``, not ``PyObject *``.
1321
Larry Hastings42d9e1b2014-01-22 05:49:11 -08001322* Use the docstring as the class docstring.
1323
1324* Although ``__new__`` and ``__init__`` functions must always
1325 accept both the ``args`` and ``kwargs`` objects, when converting
1326 you may specify any signature for these functions that you like.
1327 (If your function doesn't support keywords, the parsing function
1328 generated will throw an exception if it receives any.)
Larry Hastingsb7ccb202014-01-18 23:50:21 -08001329
Larry Hastingsbebf7352014-01-17 17:47:17 -08001330Changing and redirecting Clinic's output
1331----------------------------------------
1332
1333It can be inconvenient to have Clinic's output interspersed with
1334your conventional hand-edited C code. Luckily, Clinic is configurable:
1335you can buffer up its output for printing later (or earlier!), or write
1336its output to a separate file. You can also add a prefix or suffix to
1337every line of Clinic's generated output.
1338
1339While changing Clinic's output in this manner can be a boon to readability,
1340it may result in Clinic code using types before they are defined, or
1341your code attempting to use Clinic-generated code befire it is defined.
1342These problems can be easily solved by rearranging the declarations in your file,
1343or moving where Clinic's generated code goes. (This is why the default behavior
1344of Clinic is to output everything into the current block; while many people
1345consider this hampers readability, it will never require rearranging your
1346code to fix definition-before-use problems.)
1347
1348Let's start with defining some terminology:
1349
1350*field*
1351 A field, in this context, is a subsection of Clinic's output.
1352 For example, the ``#define`` for the ``PyMethodDef`` structure
1353 is a field, called ``methoddef_define``. Clinic has seven
1354 different fields it can output per function definition::
1355
1356 docstring_prototype
1357 docstring_definition
1358 methoddef_define
1359 impl_prototype
1360 parser_prototype
1361 parser_definition
1362 impl_definition
1363
1364 All the names are of the form ``"<a>_<b>"``,
1365 where ``"<a>"`` is the semantic object represented (the parsing function,
1366 the impl function, the docstring, or the methoddef structure) and ``"<b>"``
1367 represents what kind of statement the field is. Field names that end in
1368 ``"_prototype"``
1369 represent forward declarations of that thing, without the actual body/data
1370 of the thing; field names that end in ``"_definition"`` represent the actual
1371 definition of the thing, with the body/data of the thing. (``"methoddef"``
1372 is special, it's the only one that ends with ``"_define"``, representing that
1373 it's a preprocessor #define.)
1374
1375*destination*
1376 A destination is a place Clinic can write output to. There are
1377 five built-in destinations:
1378
1379 ``block``
1380 The default destination: printed in the output section of
1381 the current Clinic block.
1382
1383 ``buffer``
1384 A text buffer where you can save text for later. Text sent
1385 here is appended to the end of any exsiting text. It's an
1386 error to have any text left in the buffer when Clinic finishes
1387 processing a file.
1388
1389 ``file``
1390 A separate "clinic file" that will be created automatically by Clinic.
1391 The filename chosen for the file is ``{basename}.clinic{extension}``,
1392 where ``basename`` and ``extension`` were assigned the output
1393 from ``os.path.splitext()`` run on the current file. (Example:
1394 the ``file`` destination for ``_pickle.c`` would be written to
1395 ``_pickle.clinic.c``.)
1396
1397 **Important: When using a** ``file`` **destination, you**
1398 *must check in* **the generated file!**
1399
1400 ``two-pass``
1401 A buffer like ``buffer``. However, a two-pass buffer can only
1402 be written once, and it prints out all text sent to it during
1403 all of processing, even from Clinic blocks *after* the
1404
1405 ``suppress``
1406 The text is suppressed--thrown away.
1407
1408
1409Clinic defines five new directives that let you reconfigure its output.
1410
1411The first new directive is ``dump``::
1412
1413 dump <destination>
1414
1415This dumps the current contents of the named destination into the output of
1416the current block, and empties it. This only works with ``buffer`` and
1417``two-pass`` destinations.
1418
1419The second new directive is ``output``. The most basic form of ``output``
1420is like this::
1421
1422 output <field> <destination>
1423
1424This tells Clinic to output *field* to *destination*. ``output`` also
1425supports a special meta-destination, called ``everything``, which tells
1426Clinic to output *all* fields to that *destination*.
1427
1428``output`` has a number of other functions::
1429
1430 output push
1431 output pop
1432 output preset <preset>
1433
1434
1435``output push`` and ``output pop`` allow you to push and pop
1436configurations on an internal configuration stack, so that you
1437can temporarily modify the output configuration, then easily restore
1438the previous configuration. Simply push before your change to save
1439the current configuration, then pop when you wish to restore the
1440previous configuration.
1441
1442``output preset`` sets Clinic's output to one of several built-in
1443preset configurations, as follows:
1444
Larry Hastings7726ac92014-01-31 22:03:12 -08001445 ``block``
1446 Clinic's original starting configuration. Writes everything
1447 immediately after the input block.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001448
1449 Suppress the ``parser_prototype``
1450 and ``docstring_prototype``, write everything else to ``block``.
1451
1452 ``file``
1453 Designed to write everything to the "clinic file" that it can.
1454 You then ``#include`` this file near the top of your file.
1455 You may need to rearrange your file to make this work, though
1456 usually this just means creating forward declarations for various
1457 ``typedef`` and ``PyTypeObject`` definitions.
1458
1459 Suppress the ``parser_prototype``
1460 and ``docstring_prototype``, write the ``impl_definition`` to
1461 ``block``, and write everything else to ``file``.
1462
Larry Hastings0e254102014-01-26 00:42:02 -08001463 The default filename is ``"{dirname}/clinic/{basename}.h"``.
1464
Larry Hastingsbebf7352014-01-17 17:47:17 -08001465 ``buffer``
1466 Save up all most of the output from Clinic, to be written into
1467 your file near the end. For Python files implementing modules
1468 or builtin types, it's recommended that you dump the buffer
1469 just above the static structures for your module or
1470 builtin type; these are normally very near the end. Using
1471 ``buffer`` may require even more editing than ``file``, if
1472 your file has static ``PyMethodDef`` arrays defined in the
1473 middle of the file.
1474
1475 Suppress the ``parser_prototype``, ``impl_prototype``,
1476 and ``docstring_prototype``, write the ``impl_definition`` to
1477 ``block``, and write everything else to ``file``.
1478
1479 ``two-pass``
1480 Similar to the ``buffer`` preset, but writes forward declarations to
1481 the ``two-pass`` buffer, and definitions to the ``buffer``.
1482 This is similar to the ``buffer`` preset, but may require
1483 less editing than ``buffer``. Dump the ``two-pass`` buffer
1484 near the top of your file, and dump the ``buffer`` near
1485 the end just like you would when using the ``buffer`` preset.
1486
1487 Suppresses the ``impl_prototype``, write the ``impl_definition``
1488 to ``block``, write ``docstring_prototype``, ``methoddef_define``,
1489 and ``parser_prototype`` to ``two-pass``, write everything else
1490 to ``buffer``.
1491
1492 ``partial-buffer``
1493 Similar to the ``buffer`` preset, but writes more things to ``block``,
1494 only writing the really big chunks of generated code to ``buffer``.
1495 This avoids the definition-before-use problem of ``buffer`` completely,
1496 at the small cost of having slightly more stuff in the block's output.
1497 Dump the ``buffer`` near the end, just like you would when using
1498 the ``buffer`` preset.
1499
1500 Suppresses the ``impl_prototype``, write the ``docstring_definition``
Berker Peksag315e1042015-05-19 01:36:55 +03001501 and ``parser_definition`` to ``buffer``, write everything else to ``block``.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001502
1503The third new directive is ``destination``::
1504
1505 destination <name> <command> [...]
1506
1507This performs an operation on the destination named ``name``.
1508
1509There are two defined subcommands: ``new`` and ``clear``.
1510
1511The ``new`` subcommand works like this::
1512
1513 destination <name> new <type>
1514
1515This creates a new destination with name ``<name>`` and type ``<type>``.
1516
Larry Hastings0e254102014-01-26 00:42:02 -08001517There are five destination types:
Larry Hastingsbebf7352014-01-17 17:47:17 -08001518
1519 ``suppress``
1520 Throws the text away.
1521
1522 ``block``
1523 Writes the text to the current block. This is what Clinic
1524 originally did.
1525
1526 ``buffer``
1527 A simple text buffer, like the "buffer" builtin destination above.
1528
1529 ``file``
1530 A text file. The file destination takes an extra argument,
1531 a template to use for building the filename, like so:
1532
1533 destination <name> new <type> <file_template>
1534
1535 The template can use three strings internally that will be replaced
1536 by bits of the filename:
1537
Larry Hastings0e254102014-01-26 00:42:02 -08001538 {path}
1539 The full path to the file, including directory and full filename.
1540 {dirname}
1541 The name of the directory the file is in.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001542 {basename}
Larry Hastings0e254102014-01-26 00:42:02 -08001543 Just the name of the file, not including the directory.
1544 {basename_root}
1545 Basename with the extension clipped off
1546 (everything up to but not including the last '.').
1547 {basename_extension}
1548 The last '.' and everything after it. If the basename
1549 does not contain a period, this will be the empty string.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001550
1551 If there are no periods in the filename, {basename} and {filename}
1552 are the same, and {extension} is empty. "{basename}{extension}"
1553 is always exactly the same as "{filename}"."
1554
1555 ``two-pass``
1556 A two-pass buffer, like the "two-pass" builtin destination above.
1557
1558
1559The ``clear`` subcommand works like this::
1560
1561 destination <name> clear
1562
1563It removes all the accumulated text up to this point in the destination.
1564(I don't know what you'd need this for, but I thought maybe it'd be
1565useful while someone's experimenting.)
1566
1567The fourth new directive is ``set``::
1568
1569 set line_prefix "string"
1570 set line_suffix "string"
1571
1572``set`` lets you set two internal variables in Clinic.
1573``line_prefix`` is a string that will be prepended to every line of Clinic's output;
1574``line_suffix`` is a string that will be appended to every line of Clinic's output.
1575
Senthil Kumaranb4760ef2015-06-14 17:35:37 -07001576Both of these support two format strings:
Larry Hastingsbebf7352014-01-17 17:47:17 -08001577
1578 ``{block comment start}``
1579 Turns into the string ``/*``, the start-comment text sequence for C files.
1580
1581 ``{block comment end}``
1582 Turns into the string ``*/``, the end-comment text sequence for C files.
1583
1584The final new directive is one you shouldn't need to use directly,
1585called ``preserve``::
1586
1587 preserve
1588
1589This tells Clinic that the current contents of the output should be kept, unmodifed.
1590This is used internally by Clinic when dumping output into ``file`` files; wrapping
1591it in a Clinic block lets Clinic use its existing checksum functionality to ensure
1592the file was not modified by hand before it gets overwritten.
1593
1594
Larry Hastings7726ac92014-01-31 22:03:12 -08001595The #ifdef trick
1596----------------------------------------------
1597
1598If you're converting a function that isn't available on all platforms,
1599there's a trick you can use to make life a little easier. The existing
1600code probably looks like this::
1601
1602 #ifdef HAVE_FUNCTIONNAME
1603 static module_functionname(...)
1604 {
1605 ...
1606 }
1607 #endif /* HAVE_FUNCTIONNAME */
1608
1609And then in the ``PyMethodDef`` structure at the bottom the existing code
1610will have::
1611
1612 #ifdef HAVE_FUNCTIONNAME
1613 {'functionname', ... },
1614 #endif /* HAVE_FUNCTIONNAME */
1615
1616In this scenario, you should enclose the body of your impl function inside the ``#ifdef``,
1617like so::
1618
1619 #ifdef HAVE_FUNCTIONNAME
1620 /*[clinic input]
1621 module.functionname
1622 ...
1623 [clinic start generated code]*/
1624 static module_functionname(...)
1625 {
1626 ...
1627 }
1628 #endif /* HAVE_FUNCTIONNAME */
1629
1630Then, remove those three lines from the ``PyMethodDef`` structure,
1631replacing them with the macro Argument Clinic generated::
1632
1633 MODULE_FUNCTIONNAME_METHODDEF
1634
1635(You can find the real name for this macro inside the generated code.
1636Or you can calculate it yourself: it's the name of your function as defined
1637on the first line of your block, but with periods changed to underscores,
1638uppercased, and ``"_METHODDEF"`` added to the end.)
1639
1640Perhaps you're wondering: what if ``HAVE_FUNCTIONNAME`` isn't defined?
1641The ``MODULE_FUNCTIONNAME_METHODDEF`` macro won't be defined either!
1642
1643Here's where Argument Clinic gets very clever. It actually detects that the
1644Argument Clinic block might be deactivated by the ``#ifdef``. When that
1645happens, it generates a little extra code that looks like this::
1646
1647 #ifndef MODULE_FUNCTIONNAME_METHODDEF
1648 #define MODULE_FUNCTIONNAME_METHODDEF
1649 #endif /* !defined(MODULE_FUNCTIONNAME_METHODDEF) */
1650
1651That means the macro always works. If the function is defined, this turns
1652into the correct structure, including the trailing comma. If the function is
1653undefined, this turns into nothing.
1654
1655However, this causes one ticklish problem: where should Argument Clinic put this
1656extra code when using the "block" output preset? It can't go in the output block,
1657because that could be decativated by the ``#ifdef``. (That's the whole point!)
1658
1659In this situation, Argument Clinic writes the extra code to the "buffer" destination.
1660This may mean that you get a complaint from Argument Clinic::
1661
1662 Warning in file "Modules/posixmodule.c" on line 12357:
1663 Destination buffer 'buffer' not empty at end of file, emptying.
1664
1665When this happens, just open your file, find the ``dump buffer`` block that
1666Argument Clinic added to your file (it'll be at the very bottom), then
1667move it above the ``PyMethodDef`` structure where that macro is used.
1668
1669
1670
Larry Hastingsbebf7352014-01-17 17:47:17 -08001671Using Argument Clinic in Python files
Larry Hastings78cf85c2014-01-04 12:44:57 -08001672-------------------------------------
1673
1674It's actually possible to use Argument Clinic to preprocess Python files.
1675There's no point to using Argument Clinic blocks, of course, as the output
1676wouldn't make any sense to the Python interpreter. But using Argument Clinic
1677to run Python blocks lets you use Python as a Python preprocessor!
1678
1679Since Python comments are different from C comments, Argument Clinic
1680blocks embedded in Python files look slightly different. They look like this::
1681
Larry Hastings61272b72014-01-07 12:41:53 -08001682 #/*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001683 #print("def foo(): pass")
Larry Hastings61272b72014-01-07 12:41:53 -08001684 #[python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001685 def foo(): pass
1686 #/*[python checksum:...]*/