blob: caa497521c3d30d89e6de093f456d8e6252ea4eb [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
Martin Panter1050d2d2016-07-26 11:18:21 +0200155 following format units:
156
157 .. code-block:: none
Larry Hastings78cf85c2014-01-04 12:44:57 -0800158
159 O&
160 O!
161 es
162 es#
163 et
164 et#
165
Larry Hastings6d2ea212014-01-05 02:50:45 -0800166 or if it has multiple calls to :c:func:`PyArg_ParseTuple`,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800167 you should choose a different function. Argument Clinic *does*
168 support all of these scenarios. But these are advanced
169 topics--let's do something simpler for your first function.
170
Larry Hastings4a55fc52014-01-12 11:09:57 -0800171 Also, if the function has multiple calls to :c:func:`PyArg_ParseTuple`
172 or :c:func:`PyArg_ParseTupleAndKeywords` where it supports different
173 types for the same argument, or if the function uses something besides
174 PyArg_Parse functions to parse its arguments, it probably
175 isn't suitable for conversion to Argument Clinic. Argument Clinic
176 doesn't support generic functions or polymorphic parameters.
177
Larry Hastings78cf85c2014-01-04 12:44:57 -08001783. Add the following boilerplate above the function, creating our block::
179
Larry Hastings61272b72014-01-07 12:41:53 -0800180 /*[clinic input]
181 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800182
1834. Cut the docstring and paste it in between the ``[clinic]`` lines,
184 removing all the junk that makes it a properly quoted C string.
185 When you're done you should have just the text, based at the left
186 margin, with no line wider than 80 characters.
187 (Argument Clinic will preserve indents inside the docstring.)
188
Larry Hastings2a727912014-01-16 11:32:01 -0800189 If the old docstring had a first line that looked like a function
190 signature, throw that line away. (The docstring doesn't need it
191 anymore--when you use ``help()`` on your builtin in the future,
192 the first line will be built automatically based on the function's
193 signature.)
194
Larry Hastings78cf85c2014-01-04 12:44:57 -0800195 Sample::
196
Larry Hastings61272b72014-01-07 12:41:53 -0800197 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800198 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800199 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800200
2015. If your docstring doesn't have a "summary" line, Argument Clinic will
202 complain. So let's make sure it has one. The "summary" line should
203 be a paragraph consisting of a single 80-column line
204 at the beginning of the docstring.
205
Larry Hastings6d2ea212014-01-05 02:50:45 -0800206 (Our example docstring consists solely of a summary line, so the sample
Larry Hastings78cf85c2014-01-04 12:44:57 -0800207 code doesn't have to change for this step.)
208
2096. Above the docstring, enter the name of the function, followed
210 by a blank line. This should be the Python name of the function,
211 and should be the full dotted path
212 to the function--it should start with the name of the module,
213 include any sub-modules, and if the function is a method on
214 a class it should include the class name too.
215
216 Sample::
217
Larry Hastings61272b72014-01-07 12:41:53 -0800218 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800219 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800220
221 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800222 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800223
2247. If this is the first time that module or class has been used with Argument
225 Clinic in this C file,
226 you must declare the module and/or class. Proper Argument Clinic hygiene
227 prefers declaring these in a separate block somewhere near the
228 top of the C file, in the same way that include files and statics go at
229 the top. (In our sample code we'll just show the two blocks next to
230 each other.)
231
Larry Hastings4a55fc52014-01-12 11:09:57 -0800232 The name of the class and module should be the same as the one
233 seen by Python. Check the name defined in the :c:type:`PyModuleDef`
234 or :c:type:`PyTypeObject` as appropriate.
235
Larry Hastings0e254102014-01-26 00:42:02 -0800236 When you declare a class, you must also specify two aspects of its type
237 in C: the type declaration you'd use for a pointer to an instance of
238 this class, and a pointer to the :c:type:`PyTypeObject` for this class.
239
240 Sample::
241
242 /*[clinic input]
243 module _pickle
244 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
245 [clinic start generated code]*/
246
247 /*[clinic input]
248 _pickle.Pickler.dump
249
250 Write a pickled representation of obj to the open file.
251 [clinic start generated code]*/
252
253
Larry Hastings4a55fc52014-01-12 11:09:57 -0800254
Larry Hastings78cf85c2014-01-04 12:44:57 -0800255
2568. Declare each of the parameters to the function. Each parameter
257 should get its own line. All the parameter lines should be
258 indented from the function name and the docstring.
259
260 The general form of these parameter lines is as follows::
261
262 name_of_parameter: converter
263
264 If the parameter has a default value, add that after the
265 converter::
266
267 name_of_parameter: converter = default_value
268
Larry Hastings2a727912014-01-16 11:32:01 -0800269 Argument Clinic's support for "default values" is quite sophisticated;
270 please see :ref:`the section below on default values <default_values>`
271 for more information.
272
Larry Hastings78cf85c2014-01-04 12:44:57 -0800273 Add a blank line below the parameters.
274
275 What's a "converter"? It establishes both the type
276 of the variable used in C, and the method to convert the Python
277 value into a C value at runtime.
278 For now you're going to use what's called a "legacy converter"--a
279 convenience syntax intended to make porting old code into Argument
280 Clinic easier.
281
282 For each parameter, copy the "format unit" for that
283 parameter from the ``PyArg_Parse()`` format argument and
284 specify *that* as its converter, as a quoted
285 string. ("format unit" is the formal name for the one-to-three
286 character substring of the ``format`` parameter that tells
287 the argument parsing function what the type of the variable
Larry Hastings6d2ea212014-01-05 02:50:45 -0800288 is and how to convert it. For more on format units please
289 see :ref:`arg-parsing`.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800290
291 For multicharacter format units like ``z#``, use the
292 entire two-or-three character string.
293
294 Sample::
295
Larry Hastings0e254102014-01-26 00:42:02 -0800296 /*[clinic input]
297 module _pickle
298 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
299 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800300
Larry Hastings0e254102014-01-26 00:42:02 -0800301 /*[clinic input]
302 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800303
304 obj: 'O'
305
306 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800307 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800308
3099. If your function has ``|`` in the format string, meaning some
310 parameters have default values, you can ignore it. Argument
311 Clinic infers which parameters are optional based on whether
312 or not they have default values.
313
314 If your function has ``$`` in the format string, meaning it
315 takes keyword-only arguments, specify ``*`` on a line by
316 itself before the first keyword-only argument, indented the
317 same as the parameter lines.
318
Larry Hastings0e254102014-01-26 00:42:02 -0800319 (``_pickle.Pickler.dump`` has neither, so our sample is unchanged.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800320
321
Larry Hastings6d2ea212014-01-05 02:50:45 -080032210. If the existing C function calls :c:func:`PyArg_ParseTuple`
323 (as opposed to :c:func:`PyArg_ParseTupleAndKeywords`), then all its
Larry Hastings78cf85c2014-01-04 12:44:57 -0800324 arguments are positional-only.
325
326 To mark all parameters as positional-only in Argument Clinic,
327 add a ``/`` on a line by itself after the last parameter,
328 indented the same as the parameter lines.
329
Larry Hastings6d2ea212014-01-05 02:50:45 -0800330 Currently this is all-or-nothing; either all parameters are
331 positional-only, or none of them are. (In the future Argument
332 Clinic may relax this restriction.)
333
Larry Hastings78cf85c2014-01-04 12:44:57 -0800334 Sample::
335
Larry Hastings61272b72014-01-07 12:41:53 -0800336 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800337 module _pickle
338 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800339 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800340
Larry Hastings61272b72014-01-07 12:41:53 -0800341 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800342 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800343
344 obj: 'O'
345 /
346
347 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800348 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800349
Larry Hastings6d2ea212014-01-05 02:50:45 -080035011. It's helpful to write a per-parameter docstring for each parameter.
351 But per-parameter docstrings are optional; you can skip this step
352 if you prefer.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800353
Larry Hastings6d2ea212014-01-05 02:50:45 -0800354 Here's how to add a per-parameter docstring. The first line
Larry Hastings78cf85c2014-01-04 12:44:57 -0800355 of the per-parameter docstring must be indented further than the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800356 parameter definition. The left margin of this first line establishes
357 the left margin for the whole per-parameter docstring; all the text
358 you write will be outdented by this amount. You can write as much
359 text as you like, across multiple lines if you wish.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800360
361 Sample::
362
Larry Hastings61272b72014-01-07 12:41:53 -0800363 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800364 module _pickle
365 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800366 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800367
Larry Hastings61272b72014-01-07 12:41:53 -0800368 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800369 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800370
371 obj: 'O'
372 The object to be pickled.
373 /
374
375 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800376 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800377
37812. Save and close the file, then run ``Tools/clinic/clinic.py`` on it.
379 With luck everything worked and your block now has output! Reopen
380 the file in your text editor to see::
381
Larry Hastings61272b72014-01-07 12:41:53 -0800382 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800383 module _pickle
384 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800385 [clinic start generated code]*/
386 /*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800387
Larry Hastings61272b72014-01-07 12:41:53 -0800388 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800389 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800390
391 obj: 'O'
392 The object to be pickled.
393 /
394
395 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800396 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800397
Larry Hastings0e254102014-01-26 00:42:02 -0800398 PyDoc_STRVAR(_pickle_Pickler_dump__doc__,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800399 "Write a pickled representation of obj to the open file.\n"
400 "\n"
401 ...
402 static PyObject *
Larry Hastings0e254102014-01-26 00:42:02 -0800403 _pickle_Pickler_dump_impl(PicklerObject *self, PyObject *obj)
Larry Hastings61272b72014-01-07 12:41:53 -0800404 /*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800405
Larry Hastings6d2ea212014-01-05 02:50:45 -0800406 Obviously, if Argument Clinic didn't produce any output, it's because
407 it found an error in your input. Keep fixing your errors and retrying
408 until Argument Clinic processes your file without complaint.
409
Larry Hastings78cf85c2014-01-04 12:44:57 -080041013. Double-check that the argument-parsing code Argument Clinic generated
411 looks basically the same as the existing code.
412
413 First, ensure both places use the same argument-parsing function.
414 The existing code must call either
Larry Hastings6d2ea212014-01-05 02:50:45 -0800415 :c:func:`PyArg_ParseTuple` or :c:func:`PyArg_ParseTupleAndKeywords`;
Larry Hastings78cf85c2014-01-04 12:44:57 -0800416 ensure that the code generated by Argument Clinic calls the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800417 *exact* same function.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800418
Larry Hastings6d2ea212014-01-05 02:50:45 -0800419 Second, the format string passed in to :c:func:`PyArg_ParseTuple` or
420 :c:func:`PyArg_ParseTupleAndKeywords` should be *exactly* the same
421 as the hand-written one in the existing function, up to the colon
422 or semi-colon.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800423
Larry Hastings6d2ea212014-01-05 02:50:45 -0800424 (Argument Clinic always generates its format strings
425 with a ``:`` followed by the name of the function. If the
426 existing code's format string ends with ``;``, to provide
427 usage help, this change is harmless--don't worry about it.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800428
Larry Hastings6d2ea212014-01-05 02:50:45 -0800429 Third, for parameters whose format units require two arguments
430 (like a length variable, or an encoding string, or a pointer
431 to a conversion function), ensure that the second argument is
432 *exactly* the same between the two invocations.
433
434 Fourth, inside the output portion of the block you'll find a preprocessor
435 macro defining the appropriate static :c:type:`PyMethodDef` structure for
436 this builtin::
437
Larry Hastings0e254102014-01-26 00:42:02 -0800438 #define __PICKLE_PICKLER_DUMP_METHODDEF \
439 {"dump", (PyCFunction)__pickle_Pickler_dump, METH_O, __pickle_Pickler_dump__doc__},
Larry Hastings6d2ea212014-01-05 02:50:45 -0800440
441 This static structure should be *exactly* the same as the existing static
442 :c:type:`PyMethodDef` structure for this builtin.
443
444 If any of these items differ in *any way*,
445 adjust your Argument Clinic function specification and rerun
446 ``Tools/clinic/clinic.py`` until they *are* the same.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800447
448
44914. Notice that the last line of its output is the declaration
450 of your "impl" function. This is where the builtin's implementation goes.
451 Delete the existing prototype of the function you're modifying, but leave
452 the opening curly brace. Now delete its argument parsing code and the
453 declarations of all the variables it dumps the arguments into.
454 Notice how the Python arguments are now arguments to this impl function;
455 if the implementation used different names for these variables, fix it.
Larry Hastings6d2ea212014-01-05 02:50:45 -0800456
457 Let's reiterate, just because it's kind of weird. Your code should now
458 look like this::
459
460 static return_type
461 your_function_impl(...)
Larry Hastings61272b72014-01-07 12:41:53 -0800462 /*[clinic end generated code: checksum=...]*/
Larry Hastings6d2ea212014-01-05 02:50:45 -0800463 {
464 ...
465
466 Argument Clinic generated the checksum line and the function prototype just
467 above it. You should write the opening (and closing) curly braces for the
468 function, and the implementation inside.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800469
470 Sample::
471
Larry Hastings61272b72014-01-07 12:41:53 -0800472 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800473 module _pickle
474 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800475 [clinic start generated code]*/
476 /*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800477
Larry Hastings61272b72014-01-07 12:41:53 -0800478 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800479 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800480
481 obj: 'O'
482 The object to be pickled.
483 /
484
485 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800486 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800487
Larry Hastings0e254102014-01-26 00:42:02 -0800488 PyDoc_STRVAR(__pickle_Pickler_dump__doc__,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800489 "Write a pickled representation of obj to the open file.\n"
490 "\n"
491 ...
492 static PyObject *
Larry Hastings0e254102014-01-26 00:42:02 -0800493 _pickle_Pickler_dump_impl(PicklerObject *self, PyObject *obj)
Larry Hastings61272b72014-01-07 12:41:53 -0800494 /*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800495 {
496 /* Check whether the Pickler was initialized correctly (issue3664).
497 Developers often forget to call __init__() in their subclasses, which
498 would trigger a segfault without this check. */
499 if (self->write == NULL) {
500 PyErr_Format(PicklingError,
501 "Pickler.__init__() was not called by %s.__init__()",
502 Py_TYPE(self)->tp_name);
503 return NULL;
504 }
505
506 if (_Pickler_ClearBuffer(self) < 0)
507 return NULL;
508
509 ...
510
Larry Hastings6d2ea212014-01-05 02:50:45 -080051115. Remember the macro with the :c:type:`PyMethodDef` structure for this
512 function? Find the existing :c:type:`PyMethodDef` structure for this
513 function and replace it with a reference to the macro. (If the builtin
514 is at module scope, this will probably be very near the end of the file;
515 if the builtin is a class method, this will probably be below but relatively
516 near to the implementation.)
517
518 Note that the body of the macro contains a trailing comma. So when you
519 replace the existing static :c:type:`PyMethodDef` structure with the macro,
520 *don't* add a comma to the end.
521
522 Sample::
523
524 static struct PyMethodDef Pickler_methods[] = {
Larry Hastings0e254102014-01-26 00:42:02 -0800525 __PICKLE_PICKLER_DUMP_METHODDEF
526 __PICKLE_PICKLER_CLEAR_MEMO_METHODDEF
Larry Hastings6d2ea212014-01-05 02:50:45 -0800527 {NULL, NULL} /* sentinel */
528 };
529
530
53116. Compile, then run the relevant portions of the regression-test suite.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800532 This change should not introduce any new compile-time warnings or errors,
533 and there should be no externally-visible change to Python's behavior.
534
535 Well, except for one difference: ``inspect.signature()`` run on your function
536 should now provide a valid signature!
537
538 Congratulations, you've ported your first function to work with Argument Clinic!
539
Larry Hastings78cf85c2014-01-04 12:44:57 -0800540Advanced Topics
541===============
542
Larry Hastings4a55fc52014-01-12 11:09:57 -0800543Now that you've had some experience working with Argument Clinic, it's time
544for some advanced topics.
545
546
547Symbolic default values
548-----------------------
549
550The default value you provide for a parameter can't be any arbitrary
551expression. Currently the following are explicitly supported:
552
553* Numeric constants (integer and float)
554* String constants
555* ``True``, ``False``, and ``None``
556* Simple symbolic constants like ``sys.maxsize``, which must
557 start with the name of the module
558
559In case you're curious, this is implemented in ``from_builtin()``
560in ``Lib/inspect.py``.
561
562(In the future, this may need to get even more elaborate,
563to allow full expressions like ``CONSTANT - 1``.)
564
Larry Hastings78cf85c2014-01-04 12:44:57 -0800565
Larry Hastings7726ac92014-01-31 22:03:12 -0800566Renaming the C functions and variables generated by Argument Clinic
567-------------------------------------------------------------------
Larry Hastings78cf85c2014-01-04 12:44:57 -0800568
569Argument Clinic automatically names the functions it generates for you.
570Occasionally this may cause a problem, if the generated name collides with
Larry Hastings6d2ea212014-01-05 02:50:45 -0800571the name of an existing C function. There's an easy solution: override the names
572used for the C functions. Just add the keyword ``"as"``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800573to your function declaration line, followed by the function name you wish to use.
Larry Hastings6d2ea212014-01-05 02:50:45 -0800574Argument Clinic will use that function name for the base (generated) function,
575then add ``"_impl"`` to the end and use that for the name of the impl function.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800576
577For example, if we wanted to rename the C function names generated for
578``pickle.Pickler.dump``, it'd look like this::
579
Larry Hastings61272b72014-01-07 12:41:53 -0800580 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800581 pickle.Pickler.dump as pickler_dumper
582
583 ...
584
585The base function would now be named ``pickler_dumper()``,
Larry Hastings6d2ea212014-01-05 02:50:45 -0800586and the impl function would now be named ``pickler_dumper_impl()``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800587
588
Larry Hastings7726ac92014-01-31 22:03:12 -0800589Similarly, you may have a problem where you want to give a parameter
590a specific Python name, but that name may be inconvenient in C. Argument
591Clinic allows you to give a parameter different names in Python and in C,
592using the same ``"as"`` syntax::
593
594 /*[clinic input]
595 pickle.Pickler.dump
596
597 obj: object
598 file as file_obj: object
599 protocol: object = NULL
600 *
601 fix_imports: bool = True
602
603Here, the name used in Python (in the signature and the ``keywords``
604array) would be ``file``, but the C variable would be named ``file_obj``.
605
606You can use this to rename the ``self`` parameter too!
607
Larry Hastings4a55fc52014-01-12 11:09:57 -0800608
609Converting functions using PyArg_UnpackTuple
610--------------------------------------------
611
612To convert a function parsing its arguments with :c:func:`PyArg_UnpackTuple`,
613simply write out all the arguments, specifying each as an ``object``. You
614may specify the ``type`` argument to cast the type as appropriate. All
615arguments should be marked positional-only (add a ``/`` on a line by itself
616after the last argument).
617
618Currently the generated code will use :c:func:`PyArg_ParseTuple`, but this
619will change soon.
620
Larry Hastings78cf85c2014-01-04 12:44:57 -0800621Optional Groups
622---------------
623
624Some legacy functions have a tricky approach to parsing their arguments:
625they count the number of positional arguments, then use a ``switch`` statement
Larry Hastings6d2ea212014-01-05 02:50:45 -0800626to call one of several different :c:func:`PyArg_ParseTuple` calls depending on
Larry Hastings78cf85c2014-01-04 12:44:57 -0800627how many positional arguments there are. (These functions cannot accept
628keyword-only arguments.) This approach was used to simulate optional
Larry Hastings6d2ea212014-01-05 02:50:45 -0800629arguments back before :c:func:`PyArg_ParseTupleAndKeywords` was created.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800630
Larry Hastings6d2ea212014-01-05 02:50:45 -0800631While functions using this approach can often be converted to
632use :c:func:`PyArg_ParseTupleAndKeywords`, optional arguments, and default values,
633it's not always possible. Some of these legacy functions have
634behaviors :c:func:`PyArg_ParseTupleAndKeywords` doesn't directly support.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800635The most obvious example is the builtin function ``range()``, which has
636an optional argument on the *left* side of its required argument!
637Another example is ``curses.window.addch()``, which has a group of two
638arguments that must always be specified together. (The arguments are
639called ``x`` and ``y``; if you call the function passing in ``x``,
640you must also pass in ``y``--and if you don't pass in ``x`` you may not
641pass in ``y`` either.)
642
Larry Hastings6d2ea212014-01-05 02:50:45 -0800643In any case, the goal of Argument Clinic is to support argument parsing
644for all existing CPython builtins without changing their semantics.
645Therefore Argument Clinic supports
646this alternate approach to parsing, using what are called *optional groups*.
647Optional groups are groups of arguments that must all be passed in together.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800648They can be to the left or the right of the required arguments. They
649can *only* be used with positional-only parameters.
650
Larry Hastings42d9e1b2014-01-22 05:49:11 -0800651.. note:: Optional groups are *only* intended for use when converting
652 functions that make multiple calls to :c:func:`PyArg_ParseTuple`!
653 Functions that use *any* other approach for parsing arguments
654 should *almost never* be converted to Argument Clinic using
655 optional groups. Functions using optional groups currently
Martin Panterb4a2b362016-08-12 12:02:03 +0000656 cannot have accurate signatures in Python, because Python just
Larry Hastings42d9e1b2014-01-22 05:49:11 -0800657 doesn't understand the concept. Please avoid using optional
658 groups wherever possible.
659
Larry Hastings78cf85c2014-01-04 12:44:57 -0800660To specify an optional group, add a ``[`` on a line by itself before
Larry Hastings6d2ea212014-01-05 02:50:45 -0800661the parameters you wish to group together, and a ``]`` on a line by itself
662after these parameters. As an example, here's how ``curses.window.addch``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800663uses optional groups to make the first two parameters and the last
664parameter optional::
665
Larry Hastings61272b72014-01-07 12:41:53 -0800666 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800667
668 curses.window.addch
669
670 [
671 x: int
672 X-coordinate.
673 y: int
674 Y-coordinate.
675 ]
676
677 ch: object
678 Character to add.
679
680 [
681 attr: long
682 Attributes for the character.
683 ]
684 /
685
686 ...
687
688
689Notes:
690
691* For every optional group, one additional parameter will be passed into the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800692 impl function representing the group. The parameter will be an int named
693 ``group_{direction}_{number}``,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800694 where ``{direction}`` is either ``right`` or ``left`` depending on whether the group
695 is before or after the required parameters, and ``{number}`` is a monotonically
696 increasing number (starting at 1) indicating how far away the group is from
697 the required parameters. When the impl is called, this parameter will be set
698 to zero if this group was unused, and set to non-zero if this group was used.
699 (By used or unused, I mean whether or not the parameters received arguments
700 in this invocation.)
701
702* If there are no required arguments, the optional groups will behave
Larry Hastings6d2ea212014-01-05 02:50:45 -0800703 as if they're to the right of the required arguments.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800704
705* In the case of ambiguity, the argument parsing code
706 favors parameters on the left (before the required parameters).
707
Larry Hastings6d2ea212014-01-05 02:50:45 -0800708* Optional groups can only contain positional-only parameters.
709
Larry Hastings78cf85c2014-01-04 12:44:57 -0800710* Optional groups are *only* intended for legacy code. Please do not
711 use optional groups for new code.
712
713
714Using real Argument Clinic converters, instead of "legacy converters"
715---------------------------------------------------------------------
716
717To save time, and to minimize how much you need to learn
718to achieve your first port to Argument Clinic, the walkthrough above tells
Larry Hastings6d2ea212014-01-05 02:50:45 -0800719you to use "legacy converters". "Legacy converters" are a convenience,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800720designed explicitly to make porting existing code to Argument Clinic
Larry Hastings4a55fc52014-01-12 11:09:57 -0800721easier. And to be clear, their use is acceptable when porting code for
722Python 3.4.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800723
724However, in the long term we probably want all our blocks to
725use Argument Clinic's real syntax for converters. Why? A couple
726reasons:
727
728* The proper converters are far easier to read and clearer in their intent.
729* There are some format units that are unsupported as "legacy converters",
730 because they require arguments, and the legacy converter syntax doesn't
731 support specifying arguments.
732* In the future we may have a new argument parsing library that isn't
Larry Hastings6d2ea212014-01-05 02:50:45 -0800733 restricted to what :c:func:`PyArg_ParseTuple` supports; this flexibility
734 won't be available to parameters using legacy converters.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800735
Larry Hastings4a55fc52014-01-12 11:09:57 -0800736Therefore, if you don't mind a little extra effort, please use the normal
737converters instead of legacy converters.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800738
739In a nutshell, the syntax for Argument Clinic (non-legacy) converters
740looks like a Python function call. However, if there are no explicit
741arguments to the function (all functions take their default values),
742you may omit the parentheses. Thus ``bool`` and ``bool()`` are exactly
Larry Hastings6d2ea212014-01-05 02:50:45 -0800743the same converters.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800744
Larry Hastings6d2ea212014-01-05 02:50:45 -0800745All arguments to Argument Clinic converters are keyword-only.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800746All Argument Clinic converters accept the following arguments:
747
Larry Hastings2a727912014-01-16 11:32:01 -0800748 ``c_default``
749 The default value for this parameter when defined in C.
750 Specifically, this will be the initializer for the variable declared
751 in the "parse function". See :ref:`the section on default values <default_values>`
752 for how to use this.
753 Specified as a string.
Larry Hastings4a55fc52014-01-12 11:09:57 -0800754
Larry Hastings2a727912014-01-16 11:32:01 -0800755 ``annotation``
756 The annotation value for this parameter. Not currently supported,
757 because PEP 8 mandates that the Python library may not use
758 annotations.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800759
Larry Hastings2a727912014-01-16 11:32:01 -0800760In addition, some converters accept additional arguments. Here is a list
761of these arguments, along with their meanings:
Larry Hastings78cf85c2014-01-04 12:44:57 -0800762
Larry Hastings38337d12015-05-07 23:30:09 -0700763 ``accept``
764 A set of Python types (and possibly pseudo-types);
765 this restricts the allowable Python argument to values of these types.
766 (This is not a general-purpose facility; as a rule it only supports
767 specific lists of types as shown in the legacy converter table.)
768
769 To accept ``None``, add ``NoneType`` to this set.
770
Larry Hastings2a727912014-01-16 11:32:01 -0800771 ``bitwise``
772 Only supported for unsigned integers. The native integer value of this
773 Python argument will be written to the parameter without any range checking,
774 even for negative values.
Larry Hastings4a55fc52014-01-12 11:09:57 -0800775
Larry Hastings2a727912014-01-16 11:32:01 -0800776 ``converter``
777 Only supported by the ``object`` converter. Specifies the name of a
778 :ref:`C "converter function" <o_ampersand>`
779 to use to convert this object to a native type.
780
781 ``encoding``
782 Only supported for strings. Specifies the encoding to use when converting
783 this string from a Python str (Unicode) value into a C ``char *`` value.
784
Larry Hastings2a727912014-01-16 11:32:01 -0800785
786 ``subclass_of``
787 Only supported for the ``object`` converter. Requires that the Python
788 value be a subclass of a Python type, as expressed in C.
789
Larry Hastings38337d12015-05-07 23:30:09 -0700790 ``type``
791 Only supported for the ``object`` and ``self`` converters. Specifies
Larry Hastings2a727912014-01-16 11:32:01 -0800792 the C type that will be used to declare the variable. Default value is
793 ``"PyObject *"``.
794
Larry Hastings2a727912014-01-16 11:32:01 -0800795 ``zeroes``
796 Only supported for strings. If true, embedded NUL bytes (``'\\0'``) are
Larry Hastings38337d12015-05-07 23:30:09 -0700797 permitted inside the value. The length of the string will be passed in
798 to the impl function, just after the string parameter, as a parameter named
799 ``<parameter_name>_length``.
Larry Hastings2a727912014-01-16 11:32:01 -0800800
801Please note, not every possible combination of arguments will work.
Larry Hastings38337d12015-05-07 23:30:09 -0700802Usually these arguments are implemented by specific ``PyArg_ParseTuple``
Larry Hastings2a727912014-01-16 11:32:01 -0800803*format units*, with specific behavior. For example, currently you cannot
Larry Hastings38337d12015-05-07 23:30:09 -0700804call ``unsigned_short`` without also specifying ``bitwise=True``.
805Although it's perfectly reasonable to think this would work, these semantics don't
Larry Hastings2a727912014-01-16 11:32:01 -0800806map to any existing format unit. So Argument Clinic doesn't support it. (Or, at
807least, not yet.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800808
809Below is a table showing the mapping of legacy converters into real
810Argument Clinic converters. On the left is the legacy converter,
811on the right is the text you'd replace it with.
812
813========= =================================================================================
Larry Hastingsb7ccb202014-01-18 23:50:21 -0800814``'B'`` ``unsigned_char(bitwise=True)``
815``'b'`` ``unsigned_char``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800816``'c'`` ``char``
Larry Hastings38337d12015-05-07 23:30:09 -0700817``'C'`` ``int(accept={str})``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800818``'d'`` ``double``
819``'D'`` ``Py_complex``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800820``'es'`` ``str(encoding='name_of_encoding')``
Larry Hastings38337d12015-05-07 23:30:09 -0700821``'es#'`` ``str(encoding='name_of_encoding', zeroes=True)``
822``'et'`` ``str(encoding='name_of_encoding', accept={bytes, bytearray, str})``
823``'et#'`` ``str(encoding='name_of_encoding', accept={bytes, bytearray, str}, zeroes=True)``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800824``'f'`` ``float``
825``'h'`` ``short``
Larry Hastings4a55fc52014-01-12 11:09:57 -0800826``'H'`` ``unsigned_short(bitwise=True)``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800827``'i'`` ``int``
Larry Hastings4a55fc52014-01-12 11:09:57 -0800828``'I'`` ``unsigned_int(bitwise=True)``
829``'k'`` ``unsigned_long(bitwise=True)``
830``'K'`` ``unsigned_PY_LONG_LONG(bitwise=True)``
Tal Einat97fceee2015-05-16 14:12:15 +0300831``'l'`` ``long``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800832``'L'`` ``PY_LONG_LONG``
833``'n'`` ``Py_ssize_t``
Larry Hastings38337d12015-05-07 23:30:09 -0700834``'O'`` ``object``
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')``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800837``'p'`` ``bool``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800838``'S'`` ``PyBytesObject``
839``'s'`` ``str``
Larry Hastings38337d12015-05-07 23:30:09 -0700840``'s#'`` ``str(zeroes=True)``
841``'s*'`` ``Py_buffer(accept={buffer, str})``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800842``'U'`` ``unicode``
Larry Hastings38337d12015-05-07 23:30:09 -0700843``'u'`` ``Py_UNICODE``
844``'u#'`` ``Py_UNICODE(zeroes=True)``
845``'w*'`` ``Py_buffer(accept={rwbuffer})``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800846``'Y'`` ``PyByteArrayObject``
Larry Hastings38337d12015-05-07 23:30:09 -0700847``'y'`` ``str(accept={bytes})``
848``'y#'`` ``str(accept={robuffer}, zeroes=True)``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800849``'y*'`` ``Py_buffer``
Larry Hastings38337d12015-05-07 23:30:09 -0700850``'Z'`` ``Py_UNICODE(accept={str, NoneType})``
851``'Z#'`` ``Py_UNICODE(accept={str, NoneType}, zeroes=True)``
852``'z'`` ``str(accept={str, NoneType})``
853``'z#'`` ``str(accept={str, NoneType}, zeroes=True)``
854``'z*'`` ``Py_buffer(accept={buffer, str, NoneType})``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800855========= =================================================================================
856
857As an example, here's our sample ``pickle.Pickler.dump`` using the proper
858converter::
859
Larry Hastings61272b72014-01-07 12:41:53 -0800860 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800861 pickle.Pickler.dump
862
863 obj: object
864 The object to be pickled.
865 /
866
867 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800868 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800869
870Argument Clinic will show you all the converters it has
871available. For each converter it'll show you all the parameters
872it accepts, along with the default value for each parameter.
873Just run ``Tools/clinic/clinic.py --converters`` to see the full list.
874
Larry Hastings4a55fc52014-01-12 11:09:57 -0800875Py_buffer
876---------
877
878When using the ``Py_buffer`` converter
Larry Hastings0191be32014-01-12 13:57:36 -0800879(or the ``'s*'``, ``'w*'``, ``'*y'``, or ``'z*'`` legacy converters),
880you *must* not call :c:func:`PyBuffer_Release` on the provided buffer.
881Argument Clinic generates code that does it for you (in the parsing function).
882
Larry Hastings4a55fc52014-01-12 11:09:57 -0800883
Larry Hastings78cf85c2014-01-04 12:44:57 -0800884
885Advanced converters
886-------------------
887
Donald Stufft8b852f12014-05-20 12:58:38 -0400888Remember those format units you skipped for your first
Larry Hastings78cf85c2014-01-04 12:44:57 -0800889time because they were advanced? Here's how to handle those too.
890
891The trick is, all those format units take arguments--either
892conversion functions, or types, or strings specifying an encoding.
893(But "legacy converters" don't support arguments. That's why we
894skipped them for your first function.) The argument you specified
895to the format unit is now an argument to the converter; this
Larry Hastings77561cc2014-01-07 12:13:13 -0800896argument is either ``converter`` (for ``O&``), ``subclass_of`` (for ``O!``),
Larry Hastings78cf85c2014-01-04 12:44:57 -0800897or ``encoding`` (for all the format units that start with ``e``).
898
Larry Hastings77561cc2014-01-07 12:13:13 -0800899When using ``subclass_of``, you may also want to use the other
900custom argument for ``object()``: ``type``, which lets you set the type
901actually used for the parameter. For example, if you want to ensure
902that the object is a subclass of ``PyUnicode_Type``, you probably want
903to use the converter ``object(type='PyUnicodeObject *', subclass_of='&PyUnicode_Type')``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800904
Larry Hastings77561cc2014-01-07 12:13:13 -0800905One possible problem with using Argument Clinic: it takes away some possible
906flexibility for the format units starting with ``e``. When writing a
907``PyArg_Parse`` call by hand, you could theoretically decide at runtime what
Larry Hastings6d2ea212014-01-05 02:50:45 -0800908encoding string to pass in to :c:func:`PyArg_ParseTuple`. But now this string must
Larry Hastings77561cc2014-01-07 12:13:13 -0800909be hard-coded at Argument-Clinic-preprocessing-time. This limitation is deliberate;
910it made supporting this format unit much easier, and may allow for future optimizations.
911This restriction doesn't seem unreasonable; CPython itself always passes in static
Larry Hastings6d2ea212014-01-05 02:50:45 -0800912hard-coded encoding strings for parameters whose format units start with ``e``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800913
914
Larry Hastings2a727912014-01-16 11:32:01 -0800915.. _default_values:
916
917Parameter default values
918------------------------
919
920Default values for parameters can be any of a number of values.
921At their simplest, they can be string, int, or float literals::
922
923 foo: str = "abc"
924 bar: int = 123
925 bat: float = 45.6
926
927They can also use any of Python's built-in constants::
928
929 yep: bool = True
930 nope: bool = False
931 nada: object = None
932
933There's also special support for a default value of ``NULL``, and
934for simple expressions, documented in the following sections.
935
936
937The ``NULL`` default value
938--------------------------
939
940For string and object parameters, you can set them to ``None`` to indicate
941that there's no default. However, that means the C variable will be
942initialized to ``Py_None``. For convenience's sakes, there's a special
943value called ``NULL`` for just this reason: from Python's perspective it
944behaves like a default value of ``None``, but the C variable is initialized
945with ``NULL``.
946
947Expressions specified as default values
948---------------------------------------
949
950The default value for a parameter can be more than just a literal value.
951It can be an entire expression, using math operators and looking up attributes
952on objects. However, this support isn't exactly simple, because of some
953non-obvious semantics.
954
955Consider the following example::
956
957 foo: Py_ssize_t = sys.maxsize - 1
958
959``sys.maxsize`` can have different values on different platforms. Therefore
960Argument Clinic can't simply evaluate that expression locally and hard-code it
961in C. So it stores the default in such a way that it will get evaluated at
962runtime, when the user asks for the function's signature.
963
964What namespace is available when the expression is evaluated? It's evaluated
965in the context of the module the builtin came from. So, if your module has an
966attribute called "``max_widgets``", you may simply use it::
967
968 foo: Py_ssize_t = max_widgets
969
970If the symbol isn't found in the current module, it fails over to looking in
971``sys.modules``. That's how it can find ``sys.maxsize`` for example. (Since you
972don't know in advance what modules the user will load into their interpreter,
973it's best to restrict yourself to modules that are preloaded by Python itself.)
974
975Evaluating default values only at runtime means Argument Clinic can't compute
976the correct equivalent C default value. So you need to tell it explicitly.
977When you use an expression, you must also specify the equivalent expression
978in C, using the ``c_default`` parameter to the converter::
979
980 foo: Py_ssize_t(c_default="PY_SSIZE_T_MAX - 1") = sys.maxsize - 1
981
982Another complication: Argument Clinic can't know in advance whether or not the
983expression you supply is valid. It parses it to make sure it looks legal, but
984it can't *actually* know. You must be very careful when using expressions to
985specify values that are guaranteed to be valid at runtime!
986
987Finally, because expressions must be representable as static C values, there
988are many restrictions on legal expressions. Here's a list of Python features
989you're not permitted to use:
990
991* Function calls.
992* Inline if statements (``3 if foo else 5``).
993* Automatic sequence unpacking (``*[1, 2, 3]``).
994* List/set/dict comprehensions and generator expressions.
995* Tuple/list/set/dict literals.
996
997
998
Larry Hastings78cf85c2014-01-04 12:44:57 -0800999Using a return converter
1000------------------------
1001
1002By default the impl function Argument Clinic generates for you returns ``PyObject *``.
1003But your C function often computes some C type, then converts it into the ``PyObject *``
1004at the last moment. Argument Clinic handles converting your inputs from Python types
1005into native C types--why not have it convert your return value from a native C type
1006into a Python type too?
1007
1008That's what a "return converter" does. It changes your impl function to return
1009some C type, then adds code to the generated (non-impl) function to handle converting
1010that value into the appropriate ``PyObject *``.
1011
1012The syntax for return converters is similar to that of parameter converters.
1013You specify the return converter like it was a return annotation on the
1014function itself. Return converters behave much the same as parameter converters;
1015they take arguments, the arguments are all keyword-only, and if you're not changing
1016any of the default arguments you can omit the parentheses.
1017
1018(If you use both ``"as"`` *and* a return converter for your function,
1019the ``"as"`` should come before the return converter.)
1020
1021There's one additional complication when using return converters: how do you
Donald Stufft8b852f12014-05-20 12:58:38 -04001022indicate an error has occurred? Normally, a function returns a valid (non-``NULL``)
Larry Hastings78cf85c2014-01-04 12:44:57 -08001023pointer for success, and ``NULL`` for failure. But if you use an integer return converter,
1024all integers are valid. How can Argument Clinic detect an error? Its solution: each return
1025converter implicitly looks for a special value that indicates an error. If you return
1026that value, and an error has been set (``PyErr_Occurred()`` returns a true
Donald Stufft8b852f12014-05-20 12:58:38 -04001027value), then the generated code will propagate the error. Otherwise it will
Larry Hastings78cf85c2014-01-04 12:44:57 -08001028encode the value you return like normal.
1029
1030Currently Argument Clinic supports only a few return converters::
1031
Larry Hastings4a55fc52014-01-12 11:09:57 -08001032 bool
Larry Hastings78cf85c2014-01-04 12:44:57 -08001033 int
Larry Hastings4a55fc52014-01-12 11:09:57 -08001034 unsigned int
Larry Hastings78cf85c2014-01-04 12:44:57 -08001035 long
Larry Hastings4a55fc52014-01-12 11:09:57 -08001036 unsigned int
1037 size_t
Larry Hastings78cf85c2014-01-04 12:44:57 -08001038 Py_ssize_t
Larry Hastings4a55fc52014-01-12 11:09:57 -08001039 float
1040 double
Larry Hastings78cf85c2014-01-04 12:44:57 -08001041 DecodeFSDefault
1042
1043None of these take parameters. For the first three, return -1 to indicate
1044error. For ``DecodeFSDefault``, the return type is ``char *``; return a NULL
1045pointer to indicate an error.
1046
Larry Hastings4a55fc52014-01-12 11:09:57 -08001047(There's also an experimental ``NoneType`` converter, which lets you
1048return ``Py_None`` on success or ``NULL`` on failure, without having
1049to increment the reference count on ``Py_None``. I'm not sure it adds
1050enough clarity to be worth using.)
1051
Larry Hastings6d2ea212014-01-05 02:50:45 -08001052To see all the return converters Argument Clinic supports, along with
1053their parameters (if any),
1054just run ``Tools/clinic/clinic.py --converters`` for the full list.
1055
1056
Larry Hastings4a714d42014-01-14 22:22:41 -08001057Cloning existing functions
1058--------------------------
1059
1060If you have a number of functions that look similar, you may be able to
1061use Clinic's "clone" feature. When you clone an existing function,
1062you reuse:
1063
1064* its parameters, including
1065
1066 * their names,
1067
1068 * their converters, with all parameters,
1069
1070 * their default values,
1071
1072 * their per-parameter docstrings,
1073
1074 * their *kind* (whether they're positional only,
1075 positional or keyword, or keyword only), and
1076
1077* its return converter.
1078
1079The only thing not copied from the original function is its docstring;
1080the syntax allows you to specify a new docstring.
1081
1082Here's the syntax for cloning a function::
1083
1084 /*[clinic input]
1085 module.class.new_function [as c_basename] = module.class.existing_function
1086
1087 Docstring for new_function goes here.
1088 [clinic start generated code]*/
1089
1090(The functions can be in different modules or classes. I wrote
1091``module.class`` in the sample just to illustrate that you must
1092use the full path to *both* functions.)
1093
1094Sorry, there's no syntax for partially-cloning a function, or cloning a function
1095then modifying it. Cloning is an all-or nothing proposition.
1096
1097Also, the function you are cloning from must have been previously defined
1098in the current file.
1099
Larry Hastings78cf85c2014-01-04 12:44:57 -08001100Calling Python code
1101-------------------
1102
1103The rest of the advanced topics require you to write Python code
Larry Hastings6d2ea212014-01-05 02:50:45 -08001104which lives inside your C file and modifies Argument Clinic's
1105runtime state. This is simple: you simply define a Python block.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001106
1107A Python block uses different delimiter lines than an Argument
1108Clinic function block. It looks like this::
1109
Larry Hastings61272b72014-01-07 12:41:53 -08001110 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001111 # python code goes here
Larry Hastings61272b72014-01-07 12:41:53 -08001112 [python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001113
1114All the code inside the Python block is executed at the
1115time it's parsed. All text written to stdout inside the block
1116is redirected into the "output" after the block.
1117
1118As an example, here's a Python block that adds a static integer
1119variable to the C code::
1120
Larry Hastings61272b72014-01-07 12:41:53 -08001121 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001122 print('static int __ignored_unused_variable__ = 0;')
Larry Hastings61272b72014-01-07 12:41:53 -08001123 [python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001124 static int __ignored_unused_variable__ = 0;
1125 /*[python checksum:...]*/
1126
1127
1128Using a "self converter"
1129------------------------
1130
1131Argument Clinic automatically adds a "self" parameter for you
Larry Hastings0e254102014-01-26 00:42:02 -08001132using a default converter. It automatically sets the ``type``
1133of this parameter to the "pointer to an instance" you specified
1134when you declared the type. However, you can override
Larry Hastings78cf85c2014-01-04 12:44:57 -08001135Argument Clinic's converter and specify one yourself.
1136Just add your own ``self`` parameter as the first parameter in a
1137block, and ensure that its converter is an instance of
1138``self_converter`` or a subclass thereof.
1139
Larry Hastings0e254102014-01-26 00:42:02 -08001140What's the point? This lets you override the type of ``self``,
1141or give it a different default name.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001142
1143How do you specify the custom type you want to cast ``self`` to?
1144If you only have one or two functions with the same type for ``self``,
1145you can directly use Argument Clinic's existing ``self`` converter,
1146passing in the type you want to use as the ``type`` parameter::
1147
Larry Hastings61272b72014-01-07 12:41:53 -08001148 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001149
1150 _pickle.Pickler.dump
1151
1152 self: self(type="PicklerObject *")
1153 obj: object
1154 /
1155
1156 Write a pickled representation of the given object to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -08001157 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001158
1159On the other hand, if you have a lot of functions that will use the same
1160type for ``self``, it's best to create your own converter, subclassing
1161``self_converter`` but overwriting the ``type`` member::
1162
Zachary Warec1cb2272014-01-09 21:41:23 -06001163 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001164 class PicklerObject_converter(self_converter):
1165 type = "PicklerObject *"
Zachary Warec1cb2272014-01-09 21:41:23 -06001166 [python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001167
Larry Hastings61272b72014-01-07 12:41:53 -08001168 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001169
1170 _pickle.Pickler.dump
1171
1172 self: PicklerObject
1173 obj: object
1174 /
1175
1176 Write a pickled representation of the given object to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -08001177 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001178
1179
1180
1181Writing a custom converter
1182--------------------------
1183
1184As we hinted at in the previous section... you can write your own converters!
1185A converter is simply a Python class that inherits from ``CConverter``.
1186The main purpose of a custom converter is if you have a parameter using
1187the ``O&`` format unit--parsing this parameter means calling
Larry Hastings6d2ea212014-01-05 02:50:45 -08001188a :c:func:`PyArg_ParseTuple` "converter function".
Larry Hastings78cf85c2014-01-04 12:44:57 -08001189
1190Your converter class should be named ``*something*_converter``.
1191If the name follows this convention, then your converter class
1192will be automatically registered with Argument Clinic; its name
1193will be the name of your class with the ``_converter`` suffix
Larry Hastings6d2ea212014-01-05 02:50:45 -08001194stripped off. (This is accomplished with a metaclass.)
Larry Hastings78cf85c2014-01-04 12:44:57 -08001195
1196You shouldn't subclass ``CConverter.__init__``. Instead, you should
1197write a ``converter_init()`` function. ``converter_init()``
1198always accepts a ``self`` parameter; after that, all additional
1199parameters *must* be keyword-only. Any arguments passed in to
1200the converter in Argument Clinic will be passed along to your
1201``converter_init()``.
1202
1203There are some additional members of ``CConverter`` you may wish
1204to specify in your subclass. Here's the current list:
1205
1206``type``
1207 The C type to use for this variable.
1208 ``type`` should be a Python string specifying the type, e.g. ``int``.
1209 If this is a pointer type, the type string should end with ``' *'``.
1210
1211``default``
1212 The Python default value for this parameter, as a Python value.
1213 Or the magic value ``unspecified`` if there is no default.
1214
Larry Hastings78cf85c2014-01-04 12:44:57 -08001215``py_default``
1216 ``default`` as it should appear in Python code,
1217 as a string.
1218 Or ``None`` if there is no default.
1219
1220``c_default``
1221 ``default`` as it should appear in C code,
1222 as a string.
1223 Or ``None`` if there is no default.
1224
1225``c_ignored_default``
1226 The default value used to initialize the C variable when
1227 there is no default, but not specifying a default may
Larry Hastings6d2ea212014-01-05 02:50:45 -08001228 result in an "uninitialized variable" warning. This can
Larry Hastings78cf85c2014-01-04 12:44:57 -08001229 easily happen when using option groups--although
Larry Hastings6d2ea212014-01-05 02:50:45 -08001230 properly-written code will never actually use this value,
1231 the variable does get passed in to the impl, and the
1232 C compiler will complain about the "use" of the
1233 uninitialized value. This value should always be a
1234 non-empty string.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001235
1236``converter``
1237 The name of the C converter function, as a string.
1238
1239``impl_by_reference``
1240 A boolean value. If true,
1241 Argument Clinic will add a ``&`` in front of the name of
1242 the variable when passing it into the impl function.
1243
1244``parse_by_reference``
1245 A boolean value. If true,
1246 Argument Clinic will add a ``&`` in front of the name of
Larry Hastings6d2ea212014-01-05 02:50:45 -08001247 the variable when passing it into :c:func:`PyArg_ParseTuple`.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001248
1249
1250Here's the simplest example of a custom converter, from ``Modules/zlibmodule.c``::
1251
Larry Hastings61272b72014-01-07 12:41:53 -08001252 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001253
Martin Panter84544c12016-07-23 03:02:07 +00001254 class ssize_t_converter(CConverter):
1255 type = 'Py_ssize_t'
1256 converter = 'ssize_t_converter'
Larry Hastings78cf85c2014-01-04 12:44:57 -08001257
Larry Hastings61272b72014-01-07 12:41:53 -08001258 [python start generated code]*/
Martin Pantere99e9772015-11-20 08:13:35 +00001259 /*[python end generated code: output=da39a3ee5e6b4b0d input=35521e4e733823c7]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001260
Martin Panter84544c12016-07-23 03:02:07 +00001261This block adds a converter to Argument Clinic named ``ssize_t``. Parameters
1262declared as ``ssize_t`` will be declared as type ``Py_ssize_t``, and will
Martin Pantere99e9772015-11-20 08:13:35 +00001263be parsed by the ``'O&'`` format unit, which will call the
Martin Panter84544c12016-07-23 03:02:07 +00001264``ssize_t_converter`` converter function. ``ssize_t`` variables
Martin Pantere99e9772015-11-20 08:13:35 +00001265automatically support default values.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001266
1267More sophisticated custom converters can insert custom C code to
1268handle initialization and cleanup.
1269You can see more examples of custom converters in the CPython
1270source tree; grep the C files for the string ``CConverter``.
1271
1272Writing a custom return converter
1273---------------------------------
1274
1275Writing a custom return converter is much like writing
Larry Hastings6d2ea212014-01-05 02:50:45 -08001276a custom converter. Except it's somewhat simpler, because return
Larry Hastings78cf85c2014-01-04 12:44:57 -08001277converters are themselves much simpler.
1278
1279Return converters must subclass ``CReturnConverter``.
1280There are no examples yet of custom return converters,
1281because they are not widely used yet. If you wish to
1282write your own return converter, please read ``Tools/clinic/clinic.py``,
1283specifically the implementation of ``CReturnConverter`` and
1284all its subclasses.
1285
Larry Hastings4a55fc52014-01-12 11:09:57 -08001286METH_O and METH_NOARGS
1287----------------------------------------------
1288
1289To convert a function using ``METH_O``, make sure the function's
1290single argument is using the ``object`` converter, and mark the
1291arguments as positional-only::
1292
1293 /*[clinic input]
1294 meth_o_sample
1295
1296 argument: object
1297 /
1298 [clinic start generated code]*/
1299
1300
1301To convert a function using ``METH_NOARGS``, just don't specify
1302any arguments.
1303
1304You can still use a self converter, a return converter, and specify
1305a ``type`` argument to the object converter for ``METH_O``.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001306
Larry Hastingsb7ccb202014-01-18 23:50:21 -08001307tp_new and tp_init functions
1308----------------------------------------------
1309
Larry Hastings42d9e1b2014-01-22 05:49:11 -08001310You can convert ``tp_new`` and ``tp_init`` functions. Just name
1311them ``__new__`` or ``__init__`` as appropriate. Notes:
Larry Hastingsb7ccb202014-01-18 23:50:21 -08001312
1313* The function name generated for ``__new__`` doesn't end in ``__new__``
1314 like it would by default. It's just the name of the class, converted
1315 into a valid C identifier.
1316
1317* No ``PyMethodDef`` ``#define`` is generated for these functions.
1318
1319* ``__init__`` functions return ``int``, not ``PyObject *``.
1320
Larry Hastings42d9e1b2014-01-22 05:49:11 -08001321* Use the docstring as the class docstring.
1322
1323* Although ``__new__`` and ``__init__`` functions must always
1324 accept both the ``args`` and ``kwargs`` objects, when converting
1325 you may specify any signature for these functions that you like.
1326 (If your function doesn't support keywords, the parsing function
1327 generated will throw an exception if it receives any.)
Larry Hastingsb7ccb202014-01-18 23:50:21 -08001328
Larry Hastingsbebf7352014-01-17 17:47:17 -08001329Changing and redirecting Clinic's output
1330----------------------------------------
1331
1332It can be inconvenient to have Clinic's output interspersed with
1333your conventional hand-edited C code. Luckily, Clinic is configurable:
1334you can buffer up its output for printing later (or earlier!), or write
1335its output to a separate file. You can also add a prefix or suffix to
1336every line of Clinic's generated output.
1337
1338While changing Clinic's output in this manner can be a boon to readability,
1339it may result in Clinic code using types before they are defined, or
Martin Panterb4a2b362016-08-12 12:02:03 +00001340your code attempting to use Clinic-generated code before it is defined.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001341These problems can be easily solved by rearranging the declarations in your file,
1342or moving where Clinic's generated code goes. (This is why the default behavior
1343of Clinic is to output everything into the current block; while many people
1344consider this hampers readability, it will never require rearranging your
1345code to fix definition-before-use problems.)
1346
1347Let's start with defining some terminology:
1348
1349*field*
1350 A field, in this context, is a subsection of Clinic's output.
1351 For example, the ``#define`` for the ``PyMethodDef`` structure
1352 is a field, called ``methoddef_define``. Clinic has seven
1353 different fields it can output per function definition::
1354
1355 docstring_prototype
1356 docstring_definition
1357 methoddef_define
1358 impl_prototype
1359 parser_prototype
1360 parser_definition
1361 impl_definition
1362
1363 All the names are of the form ``"<a>_<b>"``,
1364 where ``"<a>"`` is the semantic object represented (the parsing function,
1365 the impl function, the docstring, or the methoddef structure) and ``"<b>"``
1366 represents what kind of statement the field is. Field names that end in
1367 ``"_prototype"``
1368 represent forward declarations of that thing, without the actual body/data
1369 of the thing; field names that end in ``"_definition"`` represent the actual
1370 definition of the thing, with the body/data of the thing. (``"methoddef"``
1371 is special, it's the only one that ends with ``"_define"``, representing that
1372 it's a preprocessor #define.)
1373
1374*destination*
1375 A destination is a place Clinic can write output to. There are
1376 five built-in destinations:
1377
1378 ``block``
1379 The default destination: printed in the output section of
1380 the current Clinic block.
1381
1382 ``buffer``
1383 A text buffer where you can save text for later. Text sent
Martin Panterb4a2b362016-08-12 12:02:03 +00001384 here is appended to the end of any existing text. It's an
Larry Hastingsbebf7352014-01-17 17:47:17 -08001385 error to have any text left in the buffer when Clinic finishes
1386 processing a file.
1387
1388 ``file``
1389 A separate "clinic file" that will be created automatically by Clinic.
1390 The filename chosen for the file is ``{basename}.clinic{extension}``,
1391 where ``basename`` and ``extension`` were assigned the output
1392 from ``os.path.splitext()`` run on the current file. (Example:
1393 the ``file`` destination for ``_pickle.c`` would be written to
1394 ``_pickle.clinic.c``.)
1395
1396 **Important: When using a** ``file`` **destination, you**
1397 *must check in* **the generated file!**
1398
1399 ``two-pass``
1400 A buffer like ``buffer``. However, a two-pass buffer can only
1401 be written once, and it prints out all text sent to it during
1402 all of processing, even from Clinic blocks *after* the
1403
1404 ``suppress``
1405 The text is suppressed--thrown away.
1406
1407
1408Clinic defines five new directives that let you reconfigure its output.
1409
1410The first new directive is ``dump``::
1411
1412 dump <destination>
1413
1414This dumps the current contents of the named destination into the output of
1415the current block, and empties it. This only works with ``buffer`` and
1416``two-pass`` destinations.
1417
1418The second new directive is ``output``. The most basic form of ``output``
1419is like this::
1420
1421 output <field> <destination>
1422
1423This tells Clinic to output *field* to *destination*. ``output`` also
1424supports a special meta-destination, called ``everything``, which tells
1425Clinic to output *all* fields to that *destination*.
1426
1427``output`` has a number of other functions::
1428
1429 output push
1430 output pop
1431 output preset <preset>
1432
1433
1434``output push`` and ``output pop`` allow you to push and pop
1435configurations on an internal configuration stack, so that you
1436can temporarily modify the output configuration, then easily restore
1437the previous configuration. Simply push before your change to save
1438the current configuration, then pop when you wish to restore the
1439previous configuration.
1440
1441``output preset`` sets Clinic's output to one of several built-in
1442preset configurations, as follows:
1443
Larry Hastings7726ac92014-01-31 22:03:12 -08001444 ``block``
1445 Clinic's original starting configuration. Writes everything
1446 immediately after the input block.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001447
1448 Suppress the ``parser_prototype``
1449 and ``docstring_prototype``, write everything else to ``block``.
1450
1451 ``file``
1452 Designed to write everything to the "clinic file" that it can.
1453 You then ``#include`` this file near the top of your file.
1454 You may need to rearrange your file to make this work, though
1455 usually this just means creating forward declarations for various
1456 ``typedef`` and ``PyTypeObject`` definitions.
1457
1458 Suppress the ``parser_prototype``
1459 and ``docstring_prototype``, write the ``impl_definition`` to
1460 ``block``, and write everything else to ``file``.
1461
Larry Hastings0e254102014-01-26 00:42:02 -08001462 The default filename is ``"{dirname}/clinic/{basename}.h"``.
1463
Larry Hastingsbebf7352014-01-17 17:47:17 -08001464 ``buffer``
1465 Save up all most of the output from Clinic, to be written into
1466 your file near the end. For Python files implementing modules
1467 or builtin types, it's recommended that you dump the buffer
1468 just above the static structures for your module or
1469 builtin type; these are normally very near the end. Using
1470 ``buffer`` may require even more editing than ``file``, if
1471 your file has static ``PyMethodDef`` arrays defined in the
1472 middle of the file.
1473
1474 Suppress the ``parser_prototype``, ``impl_prototype``,
1475 and ``docstring_prototype``, write the ``impl_definition`` to
1476 ``block``, and write everything else to ``file``.
1477
1478 ``two-pass``
1479 Similar to the ``buffer`` preset, but writes forward declarations to
1480 the ``two-pass`` buffer, and definitions to the ``buffer``.
1481 This is similar to the ``buffer`` preset, but may require
1482 less editing than ``buffer``. Dump the ``two-pass`` buffer
1483 near the top of your file, and dump the ``buffer`` near
1484 the end just like you would when using the ``buffer`` preset.
1485
1486 Suppresses the ``impl_prototype``, write the ``impl_definition``
1487 to ``block``, write ``docstring_prototype``, ``methoddef_define``,
1488 and ``parser_prototype`` to ``two-pass``, write everything else
1489 to ``buffer``.
1490
1491 ``partial-buffer``
1492 Similar to the ``buffer`` preset, but writes more things to ``block``,
1493 only writing the really big chunks of generated code to ``buffer``.
1494 This avoids the definition-before-use problem of ``buffer`` completely,
1495 at the small cost of having slightly more stuff in the block's output.
1496 Dump the ``buffer`` near the end, just like you would when using
1497 the ``buffer`` preset.
1498
1499 Suppresses the ``impl_prototype``, write the ``docstring_definition``
Berker Peksag315e1042015-05-19 01:36:55 +03001500 and ``parser_definition`` to ``buffer``, write everything else to ``block``.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001501
1502The third new directive is ``destination``::
1503
1504 destination <name> <command> [...]
1505
1506This performs an operation on the destination named ``name``.
1507
1508There are two defined subcommands: ``new`` and ``clear``.
1509
1510The ``new`` subcommand works like this::
1511
1512 destination <name> new <type>
1513
1514This creates a new destination with name ``<name>`` and type ``<type>``.
1515
Larry Hastings0e254102014-01-26 00:42:02 -08001516There are five destination types:
Larry Hastingsbebf7352014-01-17 17:47:17 -08001517
1518 ``suppress``
1519 Throws the text away.
1520
1521 ``block``
1522 Writes the text to the current block. This is what Clinic
1523 originally did.
1524
1525 ``buffer``
1526 A simple text buffer, like the "buffer" builtin destination above.
1527
1528 ``file``
1529 A text file. The file destination takes an extra argument,
1530 a template to use for building the filename, like so:
1531
1532 destination <name> new <type> <file_template>
1533
1534 The template can use three strings internally that will be replaced
1535 by bits of the filename:
1536
Larry Hastings0e254102014-01-26 00:42:02 -08001537 {path}
1538 The full path to the file, including directory and full filename.
1539 {dirname}
1540 The name of the directory the file is in.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001541 {basename}
Larry Hastings0e254102014-01-26 00:42:02 -08001542 Just the name of the file, not including the directory.
1543 {basename_root}
1544 Basename with the extension clipped off
1545 (everything up to but not including the last '.').
1546 {basename_extension}
1547 The last '.' and everything after it. If the basename
1548 does not contain a period, this will be the empty string.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001549
1550 If there are no periods in the filename, {basename} and {filename}
1551 are the same, and {extension} is empty. "{basename}{extension}"
1552 is always exactly the same as "{filename}"."
1553
1554 ``two-pass``
1555 A two-pass buffer, like the "two-pass" builtin destination above.
1556
1557
1558The ``clear`` subcommand works like this::
1559
1560 destination <name> clear
1561
1562It removes all the accumulated text up to this point in the destination.
1563(I don't know what you'd need this for, but I thought maybe it'd be
1564useful while someone's experimenting.)
1565
1566The fourth new directive is ``set``::
1567
1568 set line_prefix "string"
1569 set line_suffix "string"
1570
1571``set`` lets you set two internal variables in Clinic.
1572``line_prefix`` is a string that will be prepended to every line of Clinic's output;
1573``line_suffix`` is a string that will be appended to every line of Clinic's output.
1574
Donald Stufft8b852f12014-05-20 12:58:38 -04001575Both of these support two format strings:
Larry Hastingsbebf7352014-01-17 17:47:17 -08001576
1577 ``{block comment start}``
1578 Turns into the string ``/*``, the start-comment text sequence for C files.
1579
1580 ``{block comment end}``
1581 Turns into the string ``*/``, the end-comment text sequence for C files.
1582
1583The final new directive is one you shouldn't need to use directly,
1584called ``preserve``::
1585
1586 preserve
1587
Martin Pantereb995702016-07-28 01:11:04 +00001588This tells Clinic that the current contents of the output should be kept, unmodified.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001589This is used internally by Clinic when dumping output into ``file`` files; wrapping
1590it in a Clinic block lets Clinic use its existing checksum functionality to ensure
1591the file was not modified by hand before it gets overwritten.
1592
1593
Larry Hastings7726ac92014-01-31 22:03:12 -08001594The #ifdef trick
1595----------------------------------------------
1596
1597If you're converting a function that isn't available on all platforms,
1598there's a trick you can use to make life a little easier. The existing
1599code probably looks like this::
1600
1601 #ifdef HAVE_FUNCTIONNAME
1602 static module_functionname(...)
1603 {
1604 ...
1605 }
1606 #endif /* HAVE_FUNCTIONNAME */
1607
1608And then in the ``PyMethodDef`` structure at the bottom the existing code
1609will have::
1610
1611 #ifdef HAVE_FUNCTIONNAME
1612 {'functionname', ... },
1613 #endif /* HAVE_FUNCTIONNAME */
1614
1615In this scenario, you should enclose the body of your impl function inside the ``#ifdef``,
1616like so::
1617
1618 #ifdef HAVE_FUNCTIONNAME
1619 /*[clinic input]
1620 module.functionname
1621 ...
1622 [clinic start generated code]*/
1623 static module_functionname(...)
1624 {
1625 ...
1626 }
1627 #endif /* HAVE_FUNCTIONNAME */
1628
1629Then, remove those three lines from the ``PyMethodDef`` structure,
1630replacing them with the macro Argument Clinic generated::
1631
1632 MODULE_FUNCTIONNAME_METHODDEF
1633
1634(You can find the real name for this macro inside the generated code.
1635Or you can calculate it yourself: it's the name of your function as defined
1636on the first line of your block, but with periods changed to underscores,
1637uppercased, and ``"_METHODDEF"`` added to the end.)
1638
1639Perhaps you're wondering: what if ``HAVE_FUNCTIONNAME`` isn't defined?
1640The ``MODULE_FUNCTIONNAME_METHODDEF`` macro won't be defined either!
1641
1642Here's where Argument Clinic gets very clever. It actually detects that the
1643Argument Clinic block might be deactivated by the ``#ifdef``. When that
1644happens, it generates a little extra code that looks like this::
1645
1646 #ifndef MODULE_FUNCTIONNAME_METHODDEF
1647 #define MODULE_FUNCTIONNAME_METHODDEF
1648 #endif /* !defined(MODULE_FUNCTIONNAME_METHODDEF) */
1649
1650That means the macro always works. If the function is defined, this turns
1651into the correct structure, including the trailing comma. If the function is
1652undefined, this turns into nothing.
1653
1654However, this causes one ticklish problem: where should Argument Clinic put this
1655extra code when using the "block" output preset? It can't go in the output block,
Martin Panterb4a2b362016-08-12 12:02:03 +00001656because that could be deactivated by the ``#ifdef``. (That's the whole point!)
Larry Hastings7726ac92014-01-31 22:03:12 -08001657
1658In this situation, Argument Clinic writes the extra code to the "buffer" destination.
1659This may mean that you get a complaint from Argument Clinic::
1660
1661 Warning in file "Modules/posixmodule.c" on line 12357:
1662 Destination buffer 'buffer' not empty at end of file, emptying.
1663
1664When this happens, just open your file, find the ``dump buffer`` block that
1665Argument Clinic added to your file (it'll be at the very bottom), then
1666move it above the ``PyMethodDef`` structure where that macro is used.
1667
1668
1669
Larry Hastingsbebf7352014-01-17 17:47:17 -08001670Using Argument Clinic in Python files
Larry Hastings78cf85c2014-01-04 12:44:57 -08001671-------------------------------------
1672
1673It's actually possible to use Argument Clinic to preprocess Python files.
1674There's no point to using Argument Clinic blocks, of course, as the output
1675wouldn't make any sense to the Python interpreter. But using Argument Clinic
1676to run Python blocks lets you use Python as a Python preprocessor!
1677
1678Since Python comments are different from C comments, Argument Clinic
1679blocks embedded in Python files look slightly different. They look like this::
1680
Larry Hastings61272b72014-01-07 12:41:53 -08001681 #/*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001682 #print("def foo(): pass")
Larry Hastings61272b72014-01-07 12:41:53 -08001683 #[python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001684 def foo(): pass
1685 #/*[python checksum:...]*/