blob: d3c7d668959e56e92be4004bb9af89882cc06347 [file] [log] [blame]
Martin Pantercfa9bad2016-12-10 04:10:45 +00001.. highlightlang:: c
2
Ezio Melottia3642b62014-01-25 17:27:46 +02003**********************
Larry Hastings78cf85c2014-01-04 12:44:57 -08004Argument Clinic How-To
Ezio Melottia3642b62014-01-25 17:27:46 +02005**********************
Larry Hastings78cf85c2014-01-04 12:44:57 -08006
7:author: Larry Hastings
8
9
10.. topic:: Abstract
11
12 Argument Clinic is a preprocessor for CPython C files.
13 Its purpose is to automate all the boilerplate involved
14 with writing argument parsing code for "builtins".
15 This document shows you how to convert your first C
16 function to work with Argument Clinic, and then introduces
17 some advanced topics on Argument Clinic usage.
18
Larry Hastings6d2ea212014-01-05 02:50:45 -080019 Currently Argument Clinic is considered internal-only
20 for CPython. Its use is not supported for files outside
21 CPython, and no guarantees are made regarding backwards
22 compatibility for future versions. In other words: if you
23 maintain an external C extension for CPython, you're welcome
24 to experiment with Argument Clinic in your own code. But the
25 version of Argument Clinic that ships with CPython 3.5 *could*
26 be totally incompatible and break all your code.
Larry Hastings78cf85c2014-01-04 12:44:57 -080027
Larry Hastingsbebf7352014-01-17 17:47:17 -080028The Goals Of Argument Clinic
29============================
30
31Argument Clinic's primary goal
32is to take over responsibility for all argument parsing code
33inside CPython. This means that, when you convert a function
34to work with Argument Clinic, that function should no longer
Martin Panter357ed2e2016-11-21 00:15:20 +000035do any of its own argument parsingthe code generated by
Larry Hastingsbebf7352014-01-17 17:47:17 -080036Argument Clinic should be a "black box" to you, where CPython
37calls in at the top, and your code gets called at the bottom,
38with ``PyObject *args`` (and maybe ``PyObject *kwargs``)
39magically converted into the C variables and types you need.
40
41In order for Argument Clinic to accomplish its primary goal,
42it must be easy to use. Currently, working with CPython's
43argument parsing library is a chore, requiring maintaining
44redundant information in a surprising number of places.
45When you use Argument Clinic, you don't have to repeat yourself.
46
47Obviously, no one would want to use Argument Clinic unless
Martin Panter357ed2e2016-11-21 00:15:20 +000048it's solving their problem—and without creating new problems of
Larry Hastingsbebf7352014-01-17 17:47:17 -080049its own.
Larry Hastings537d7602014-01-18 01:08:50 -080050So it's paramount that Argument Clinic generate correct code.
51It'd be nice if the code was faster, too, but at the very least
52it should not introduce a major speed regression. (Eventually Argument
Martin Panter357ed2e2016-11-21 00:15:20 +000053Clinic *should* make a major speedup possible—we could
Larry Hastings537d7602014-01-18 01:08:50 -080054rewrite its code generator to produce tailor-made argument
55parsing code, rather than calling the general-purpose CPython
56argument parsing library. That would make for the fastest
57argument parsing possible!)
Larry Hastingsbebf7352014-01-17 17:47:17 -080058
59Additionally, Argument Clinic must be flexible enough to
60work with any approach to argument parsing. Python has
61some functions with some very strange parsing behaviors;
62Argument Clinic's goal is to support all of them.
63
64Finally, the original motivation for Argument Clinic was
65to provide introspection "signatures" for CPython builtins.
66It used to be, the introspection query functions would throw
67an exception if you passed in a builtin. With Argument
68Clinic, that's a thing of the past!
69
70One idea you should keep in mind, as you work with
71Argument Clinic: the more information you give it, the
72better job it'll be able to do.
73Argument Clinic is admittedly relatively simple right
74now. But as it evolves it will get more sophisticated,
75and it should be able to do many interesting and smart
76things with all the information you give it.
77
78
Larry Hastings78cf85c2014-01-04 12:44:57 -080079Basic Concepts And Usage
80========================
81
Larry Hastings6d2ea212014-01-05 02:50:45 -080082Argument Clinic ships with CPython; you'll find it in ``Tools/clinic/clinic.py``.
Martin Pantercfa9bad2016-12-10 04:10:45 +000083If you run that script, specifying a C file as an argument:
Larry Hastings78cf85c2014-01-04 12:44:57 -080084
Martin Pantercfa9bad2016-12-10 04:10:45 +000085.. code-block:: shell-session
86
87 $ python3 Tools/clinic/clinic.py foo.c
Larry Hastings78cf85c2014-01-04 12:44:57 -080088
89Argument Clinic will scan over the file looking for lines that
Martin Pantercfa9bad2016-12-10 04:10:45 +000090look exactly like this:
91
92.. code-block:: none
Larry Hastings78cf85c2014-01-04 12:44:57 -080093
Larry Hastings61272b72014-01-07 12:41:53 -080094 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -080095
96When it finds one, it reads everything up to a line that looks
Martin Pantercfa9bad2016-12-10 04:10:45 +000097exactly like this:
98
99.. code-block:: none
Larry Hastings78cf85c2014-01-04 12:44:57 -0800100
Larry Hastings61272b72014-01-07 12:41:53 -0800101 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800102
103Everything in between these two lines is input for Argument Clinic.
104All of these lines, including the beginning and ending comment
Larry Hastings6d2ea212014-01-05 02:50:45 -0800105lines, are collectively called an Argument Clinic "block".
Larry Hastings78cf85c2014-01-04 12:44:57 -0800106
107When Argument Clinic parses one of these blocks, it
108generates output. This output is rewritten into the C file
109immediately after the block, followed by a comment containing a checksum.
Martin Pantercfa9bad2016-12-10 04:10:45 +0000110The Argument Clinic block now looks like this:
111
112.. code-block:: none
Larry Hastings78cf85c2014-01-04 12:44:57 -0800113
Larry Hastings61272b72014-01-07 12:41:53 -0800114 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800115 ... clinic input goes here ...
Larry Hastings61272b72014-01-07 12:41:53 -0800116 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800117 ... clinic output goes here ...
Larry Hastings61272b72014-01-07 12:41:53 -0800118 /*[clinic end generated code: checksum=...]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800119
120If you run Argument Clinic on the same file a second time, Argument Clinic
121will discard the old output and write out the new output with a fresh checksum
122line. However, if the input hasn't changed, the output won't change either.
123
124You should never modify the output portion of an Argument Clinic block. Instead,
125change the input until it produces the output you want. (That's the purpose of the
Martin Panter357ed2e2016-11-21 00:15:20 +0000126checksumto detect if someone changed the output, as these edits would be lost
Larry Hastings6d2ea212014-01-05 02:50:45 -0800127the next time Argument Clinic writes out fresh output.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800128
129For the sake of clarity, here's the terminology we'll use with Argument Clinic:
130
Larry Hastings61272b72014-01-07 12:41:53 -0800131* The first line of the comment (``/*[clinic input]``) is the *start line*.
132* The last line of the initial comment (``[clinic start generated code]*/``) is the *end line*.
133* The last line (``/*[clinic end generated code: checksum=...]*/``) is the *checksum line*.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800134* In between the start line and the end line is the *input*.
135* In between the end line and the checksum line is the *output*.
136* All the text collectively, from the start line to the checksum line inclusively,
137 is the *block*. (A block that hasn't been successfully processed by Argument
138 Clinic yet doesn't have output or a checksum line, but it's still considered
139 a block.)
140
141
Larry Hastings78cf85c2014-01-04 12:44:57 -0800142Converting Your First Function
143==============================
144
145The best way to get a sense of how Argument Clinic works is to
Larry Hastingsbebf7352014-01-17 17:47:17 -0800146convert a function to work with it. Here, then, are the bare
147minimum steps you'd need to follow to convert a function to
148work with Argument Clinic. Note that for code you plan to
149check in to CPython, you really should take the conversion farther,
150using some of the advanced concepts you'll see later on in
151the document (like "return converters" and "self converters").
152But we'll keep it simple for this walkthrough so you can learn.
153
154Let's dive in!
Larry Hastings78cf85c2014-01-04 12:44:57 -0800155
Larry Hastings6d2ea212014-01-05 02:50:45 -08001560. Make sure you're working with a freshly updated checkout
157 of the CPython trunk.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800158
Larry Hastings6d2ea212014-01-05 02:50:45 -08001591. Find a Python builtin that calls either :c:func:`PyArg_ParseTuple`
160 or :c:func:`PyArg_ParseTupleAndKeywords`, and hasn't been converted
161 to work with Argument Clinic yet.
Larry Hastings0e254102014-01-26 00:42:02 -0800162 For my example I'm using ``_pickle.Pickler.dump()``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800163
1642. If the call to the ``PyArg_Parse`` function uses any of the
Martin Panter1050d2d2016-07-26 11:18:21 +0200165 following format units:
166
167 .. code-block:: none
Larry Hastings78cf85c2014-01-04 12:44:57 -0800168
169 O&
170 O!
171 es
172 es#
173 et
174 et#
175
Larry Hastings6d2ea212014-01-05 02:50:45 -0800176 or if it has multiple calls to :c:func:`PyArg_ParseTuple`,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800177 you should choose a different function. Argument Clinic *does*
178 support all of these scenarios. But these are advanced
Martin Panter357ed2e2016-11-21 00:15:20 +0000179 topicslet's do something simpler for your first function.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800180
Larry Hastings4a55fc52014-01-12 11:09:57 -0800181 Also, if the function has multiple calls to :c:func:`PyArg_ParseTuple`
182 or :c:func:`PyArg_ParseTupleAndKeywords` where it supports different
183 types for the same argument, or if the function uses something besides
184 PyArg_Parse functions to parse its arguments, it probably
185 isn't suitable for conversion to Argument Clinic. Argument Clinic
186 doesn't support generic functions or polymorphic parameters.
187
Larry Hastings78cf85c2014-01-04 12:44:57 -08001883. Add the following boilerplate above the function, creating our block::
189
Larry Hastings61272b72014-01-07 12:41:53 -0800190 /*[clinic input]
191 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800192
1934. Cut the docstring and paste it in between the ``[clinic]`` lines,
194 removing all the junk that makes it a properly quoted C string.
195 When you're done you should have just the text, based at the left
196 margin, with no line wider than 80 characters.
197 (Argument Clinic will preserve indents inside the docstring.)
198
Larry Hastings2a727912014-01-16 11:32:01 -0800199 If the old docstring had a first line that looked like a function
200 signature, throw that line away. (The docstring doesn't need it
Martin Panter357ed2e2016-11-21 00:15:20 +0000201 anymore—when you use ``help()`` on your builtin in the future,
Larry Hastings2a727912014-01-16 11:32:01 -0800202 the first line will be built automatically based on the function's
203 signature.)
204
Larry Hastings78cf85c2014-01-04 12:44:57 -0800205 Sample::
206
Larry Hastings61272b72014-01-07 12:41:53 -0800207 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800208 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800209 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800210
2115. If your docstring doesn't have a "summary" line, Argument Clinic will
212 complain. So let's make sure it has one. The "summary" line should
213 be a paragraph consisting of a single 80-column line
214 at the beginning of the docstring.
215
Larry Hastings6d2ea212014-01-05 02:50:45 -0800216 (Our example docstring consists solely of a summary line, so the sample
Larry Hastings78cf85c2014-01-04 12:44:57 -0800217 code doesn't have to change for this step.)
218
2196. Above the docstring, enter the name of the function, followed
220 by a blank line. This should be the Python name of the function,
221 and should be the full dotted path
Martin Panter357ed2e2016-11-21 00:15:20 +0000222 to the function—it should start with the name of the module,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800223 include any sub-modules, and if the function is a method on
224 a class it should include the class name too.
225
226 Sample::
227
Larry Hastings61272b72014-01-07 12:41:53 -0800228 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800229 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800230
231 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800232 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800233
2347. If this is the first time that module or class has been used with Argument
235 Clinic in this C file,
236 you must declare the module and/or class. Proper Argument Clinic hygiene
237 prefers declaring these in a separate block somewhere near the
238 top of the C file, in the same way that include files and statics go at
239 the top. (In our sample code we'll just show the two blocks next to
240 each other.)
241
Larry Hastings4a55fc52014-01-12 11:09:57 -0800242 The name of the class and module should be the same as the one
243 seen by Python. Check the name defined in the :c:type:`PyModuleDef`
244 or :c:type:`PyTypeObject` as appropriate.
245
Larry Hastings0e254102014-01-26 00:42:02 -0800246 When you declare a class, you must also specify two aspects of its type
247 in C: the type declaration you'd use for a pointer to an instance of
248 this class, and a pointer to the :c:type:`PyTypeObject` for this class.
249
250 Sample::
251
252 /*[clinic input]
253 module _pickle
254 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
255 [clinic start generated code]*/
256
257 /*[clinic input]
258 _pickle.Pickler.dump
259
260 Write a pickled representation of obj to the open file.
261 [clinic start generated code]*/
262
263
Larry Hastings4a55fc52014-01-12 11:09:57 -0800264
Larry Hastings78cf85c2014-01-04 12:44:57 -0800265
2668. Declare each of the parameters to the function. Each parameter
267 should get its own line. All the parameter lines should be
268 indented from the function name and the docstring.
269
270 The general form of these parameter lines is as follows::
271
272 name_of_parameter: converter
273
274 If the parameter has a default value, add that after the
275 converter::
276
277 name_of_parameter: converter = default_value
278
Larry Hastings2a727912014-01-16 11:32:01 -0800279 Argument Clinic's support for "default values" is quite sophisticated;
280 please see :ref:`the section below on default values <default_values>`
281 for more information.
282
Larry Hastings78cf85c2014-01-04 12:44:57 -0800283 Add a blank line below the parameters.
284
285 What's a "converter"? It establishes both the type
286 of the variable used in C, and the method to convert the Python
287 value into a C value at runtime.
Martin Panter357ed2e2016-11-21 00:15:20 +0000288 For now you're going to use what's called a "legacy converter"—a
Larry Hastings78cf85c2014-01-04 12:44:57 -0800289 convenience syntax intended to make porting old code into Argument
290 Clinic easier.
291
292 For each parameter, copy the "format unit" for that
293 parameter from the ``PyArg_Parse()`` format argument and
294 specify *that* as its converter, as a quoted
295 string. ("format unit" is the formal name for the one-to-three
296 character substring of the ``format`` parameter that tells
297 the argument parsing function what the type of the variable
Larry Hastings6d2ea212014-01-05 02:50:45 -0800298 is and how to convert it. For more on format units please
299 see :ref:`arg-parsing`.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800300
301 For multicharacter format units like ``z#``, use the
302 entire two-or-three character string.
303
304 Sample::
305
Larry Hastings0e254102014-01-26 00:42:02 -0800306 /*[clinic input]
307 module _pickle
308 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
309 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800310
Larry Hastings0e254102014-01-26 00:42:02 -0800311 /*[clinic input]
312 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800313
314 obj: 'O'
315
316 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800317 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800318
3199. If your function has ``|`` in the format string, meaning some
320 parameters have default values, you can ignore it. Argument
321 Clinic infers which parameters are optional based on whether
322 or not they have default values.
323
324 If your function has ``$`` in the format string, meaning it
325 takes keyword-only arguments, specify ``*`` on a line by
326 itself before the first keyword-only argument, indented the
327 same as the parameter lines.
328
Larry Hastings0e254102014-01-26 00:42:02 -0800329 (``_pickle.Pickler.dump`` has neither, so our sample is unchanged.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800330
331
Larry Hastings6d2ea212014-01-05 02:50:45 -080033210. If the existing C function calls :c:func:`PyArg_ParseTuple`
333 (as opposed to :c:func:`PyArg_ParseTupleAndKeywords`), then all its
Larry Hastings78cf85c2014-01-04 12:44:57 -0800334 arguments are positional-only.
335
336 To mark all parameters as positional-only in Argument Clinic,
337 add a ``/`` on a line by itself after the last parameter,
338 indented the same as the parameter lines.
339
Larry Hastings6d2ea212014-01-05 02:50:45 -0800340 Currently this is all-or-nothing; either all parameters are
341 positional-only, or none of them are. (In the future Argument
342 Clinic may relax this restriction.)
343
Larry Hastings78cf85c2014-01-04 12:44:57 -0800344 Sample::
345
Larry Hastings61272b72014-01-07 12:41:53 -0800346 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800347 module _pickle
348 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800349 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800350
Larry Hastings61272b72014-01-07 12:41:53 -0800351 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800352 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800353
354 obj: 'O'
355 /
356
357 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800358 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800359
Larry Hastings6d2ea212014-01-05 02:50:45 -080036011. It's helpful to write a per-parameter docstring for each parameter.
361 But per-parameter docstrings are optional; you can skip this step
362 if you prefer.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800363
Larry Hastings6d2ea212014-01-05 02:50:45 -0800364 Here's how to add a per-parameter docstring. The first line
Larry Hastings78cf85c2014-01-04 12:44:57 -0800365 of the per-parameter docstring must be indented further than the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800366 parameter definition. The left margin of this first line establishes
367 the left margin for the whole per-parameter docstring; all the text
368 you write will be outdented by this amount. You can write as much
369 text as you like, across multiple lines if you wish.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800370
371 Sample::
372
Larry Hastings61272b72014-01-07 12:41:53 -0800373 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800374 module _pickle
375 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800376 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800377
Larry Hastings61272b72014-01-07 12:41:53 -0800378 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800379 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800380
381 obj: 'O'
382 The object to be pickled.
383 /
384
385 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800386 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800387
Martin Pantera277c132016-12-10 03:49:12 +000038812. Save and close the file, then run ``Tools/clinic/clinic.py`` on
389 it. With luck everything worked---your block now has output, and
390 a ``.c.h`` file has been generated! Reopen the file in your
Martin Pantercfa9bad2016-12-10 04:10:45 +0000391 text editor to see::
Larry Hastings78cf85c2014-01-04 12:44:57 -0800392
Larry Hastings61272b72014-01-07 12:41:53 -0800393 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800394 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800395
396 obj: 'O'
397 The object to be pickled.
398 /
399
400 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800401 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800402
Larry Hastings78cf85c2014-01-04 12:44:57 -0800403 static PyObject *
Martin Pantera277c132016-12-10 03:49:12 +0000404 _pickle_Pickler_dump(PicklerObject *self, PyObject *obj)
405 /*[clinic end generated code: output=87ecad1261e02ac7 input=552eb1c0f52260d9]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800406
Larry Hastings6d2ea212014-01-05 02:50:45 -0800407 Obviously, if Argument Clinic didn't produce any output, it's because
408 it found an error in your input. Keep fixing your errors and retrying
409 until Argument Clinic processes your file without complaint.
410
Martin Pantera277c132016-12-10 03:49:12 +0000411 For readability, most of the glue code has been generated to a ``.c.h``
412 file. You'll need to include that in your original ``.c`` file,
Martin Pantercfa9bad2016-12-10 04:10:45 +0000413 typically right after the clinic module block::
Martin Pantera277c132016-12-10 03:49:12 +0000414
415 #include "clinic/_pickle.c.h"
416
Larry Hastings78cf85c2014-01-04 12:44:57 -080041713. Double-check that the argument-parsing code Argument Clinic generated
418 looks basically the same as the existing code.
419
420 First, ensure both places use the same argument-parsing function.
421 The existing code must call either
Larry Hastings6d2ea212014-01-05 02:50:45 -0800422 :c:func:`PyArg_ParseTuple` or :c:func:`PyArg_ParseTupleAndKeywords`;
Larry Hastings78cf85c2014-01-04 12:44:57 -0800423 ensure that the code generated by Argument Clinic calls the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800424 *exact* same function.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800425
Larry Hastings6d2ea212014-01-05 02:50:45 -0800426 Second, the format string passed in to :c:func:`PyArg_ParseTuple` or
427 :c:func:`PyArg_ParseTupleAndKeywords` should be *exactly* the same
428 as the hand-written one in the existing function, up to the colon
429 or semi-colon.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800430
Larry Hastings6d2ea212014-01-05 02:50:45 -0800431 (Argument Clinic always generates its format strings
432 with a ``:`` followed by the name of the function. If the
433 existing code's format string ends with ``;``, to provide
Martin Panter357ed2e2016-11-21 00:15:20 +0000434 usage help, this change is harmless—don't worry about it.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800435
Larry Hastings6d2ea212014-01-05 02:50:45 -0800436 Third, for parameters whose format units require two arguments
437 (like a length variable, or an encoding string, or a pointer
438 to a conversion function), ensure that the second argument is
439 *exactly* the same between the two invocations.
440
441 Fourth, inside the output portion of the block you'll find a preprocessor
442 macro defining the appropriate static :c:type:`PyMethodDef` structure for
443 this builtin::
444
Larry Hastings0e254102014-01-26 00:42:02 -0800445 #define __PICKLE_PICKLER_DUMP_METHODDEF \
446 {"dump", (PyCFunction)__pickle_Pickler_dump, METH_O, __pickle_Pickler_dump__doc__},
Larry Hastings6d2ea212014-01-05 02:50:45 -0800447
448 This static structure should be *exactly* the same as the existing static
449 :c:type:`PyMethodDef` structure for this builtin.
450
451 If any of these items differ in *any way*,
452 adjust your Argument Clinic function specification and rerun
453 ``Tools/clinic/clinic.py`` until they *are* the same.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800454
455
45614. Notice that the last line of its output is the declaration
457 of your "impl" function. This is where the builtin's implementation goes.
458 Delete the existing prototype of the function you're modifying, but leave
459 the opening curly brace. Now delete its argument parsing code and the
460 declarations of all the variables it dumps the arguments into.
461 Notice how the Python arguments are now arguments to this impl function;
462 if the implementation used different names for these variables, fix it.
Larry Hastings6d2ea212014-01-05 02:50:45 -0800463
464 Let's reiterate, just because it's kind of weird. Your code should now
465 look like this::
466
467 static return_type
468 your_function_impl(...)
Larry Hastings61272b72014-01-07 12:41:53 -0800469 /*[clinic end generated code: checksum=...]*/
Larry Hastings6d2ea212014-01-05 02:50:45 -0800470 {
471 ...
472
473 Argument Clinic generated the checksum line and the function prototype just
474 above it. You should write the opening (and closing) curly braces for the
475 function, and the implementation inside.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800476
477 Sample::
478
Larry Hastings61272b72014-01-07 12:41:53 -0800479 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800480 module _pickle
481 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800482 [clinic start generated code]*/
483 /*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800484
Larry Hastings61272b72014-01-07 12:41:53 -0800485 /*[clinic input]
Larry Hastings0e254102014-01-26 00:42:02 -0800486 _pickle.Pickler.dump
Larry Hastings78cf85c2014-01-04 12:44:57 -0800487
488 obj: 'O'
489 The object to be pickled.
490 /
491
492 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800493 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800494
Larry Hastings0e254102014-01-26 00:42:02 -0800495 PyDoc_STRVAR(__pickle_Pickler_dump__doc__,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800496 "Write a pickled representation of obj to the open file.\n"
497 "\n"
498 ...
499 static PyObject *
Larry Hastings0e254102014-01-26 00:42:02 -0800500 _pickle_Pickler_dump_impl(PicklerObject *self, PyObject *obj)
Larry Hastings61272b72014-01-07 12:41:53 -0800501 /*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800502 {
503 /* Check whether the Pickler was initialized correctly (issue3664).
504 Developers often forget to call __init__() in their subclasses, which
505 would trigger a segfault without this check. */
506 if (self->write == NULL) {
507 PyErr_Format(PicklingError,
508 "Pickler.__init__() was not called by %s.__init__()",
509 Py_TYPE(self)->tp_name);
510 return NULL;
511 }
512
513 if (_Pickler_ClearBuffer(self) < 0)
514 return NULL;
515
516 ...
517
Larry Hastings6d2ea212014-01-05 02:50:45 -080051815. Remember the macro with the :c:type:`PyMethodDef` structure for this
519 function? Find the existing :c:type:`PyMethodDef` structure for this
520 function and replace it with a reference to the macro. (If the builtin
521 is at module scope, this will probably be very near the end of the file;
522 if the builtin is a class method, this will probably be below but relatively
523 near to the implementation.)
524
525 Note that the body of the macro contains a trailing comma. So when you
526 replace the existing static :c:type:`PyMethodDef` structure with the macro,
527 *don't* add a comma to the end.
528
529 Sample::
530
531 static struct PyMethodDef Pickler_methods[] = {
Larry Hastings0e254102014-01-26 00:42:02 -0800532 __PICKLE_PICKLER_DUMP_METHODDEF
533 __PICKLE_PICKLER_CLEAR_MEMO_METHODDEF
Larry Hastings6d2ea212014-01-05 02:50:45 -0800534 {NULL, NULL} /* sentinel */
535 };
536
537
53816. Compile, then run the relevant portions of the regression-test suite.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800539 This change should not introduce any new compile-time warnings or errors,
540 and there should be no externally-visible change to Python's behavior.
541
542 Well, except for one difference: ``inspect.signature()`` run on your function
543 should now provide a valid signature!
544
545 Congratulations, you've ported your first function to work with Argument Clinic!
546
Larry Hastings78cf85c2014-01-04 12:44:57 -0800547Advanced Topics
548===============
549
Larry Hastings4a55fc52014-01-12 11:09:57 -0800550Now that you've had some experience working with Argument Clinic, it's time
551for some advanced topics.
552
553
554Symbolic default values
555-----------------------
556
557The default value you provide for a parameter can't be any arbitrary
558expression. Currently the following are explicitly supported:
559
560* Numeric constants (integer and float)
561* String constants
562* ``True``, ``False``, and ``None``
563* Simple symbolic constants like ``sys.maxsize``, which must
564 start with the name of the module
565
566In case you're curious, this is implemented in ``from_builtin()``
567in ``Lib/inspect.py``.
568
569(In the future, this may need to get even more elaborate,
570to allow full expressions like ``CONSTANT - 1``.)
571
Larry Hastings78cf85c2014-01-04 12:44:57 -0800572
Larry Hastings7726ac92014-01-31 22:03:12 -0800573Renaming the C functions and variables generated by Argument Clinic
574-------------------------------------------------------------------
Larry Hastings78cf85c2014-01-04 12:44:57 -0800575
576Argument Clinic automatically names the functions it generates for you.
577Occasionally this may cause a problem, if the generated name collides with
Larry Hastings6d2ea212014-01-05 02:50:45 -0800578the name of an existing C function. There's an easy solution: override the names
579used for the C functions. Just add the keyword ``"as"``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800580to your function declaration line, followed by the function name you wish to use.
Larry Hastings6d2ea212014-01-05 02:50:45 -0800581Argument Clinic will use that function name for the base (generated) function,
582then add ``"_impl"`` to the end and use that for the name of the impl function.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800583
584For example, if we wanted to rename the C function names generated for
585``pickle.Pickler.dump``, it'd look like this::
586
Larry Hastings61272b72014-01-07 12:41:53 -0800587 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800588 pickle.Pickler.dump as pickler_dumper
589
590 ...
591
592The base function would now be named ``pickler_dumper()``,
Larry Hastings6d2ea212014-01-05 02:50:45 -0800593and the impl function would now be named ``pickler_dumper_impl()``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800594
595
Larry Hastings7726ac92014-01-31 22:03:12 -0800596Similarly, you may have a problem where you want to give a parameter
597a specific Python name, but that name may be inconvenient in C. Argument
598Clinic allows you to give a parameter different names in Python and in C,
599using the same ``"as"`` syntax::
600
601 /*[clinic input]
602 pickle.Pickler.dump
603
604 obj: object
605 file as file_obj: object
606 protocol: object = NULL
607 *
608 fix_imports: bool = True
609
610Here, the name used in Python (in the signature and the ``keywords``
611array) would be ``file``, but the C variable would be named ``file_obj``.
612
613You can use this to rename the ``self`` parameter too!
614
Larry Hastings4a55fc52014-01-12 11:09:57 -0800615
616Converting functions using PyArg_UnpackTuple
617--------------------------------------------
618
619To convert a function parsing its arguments with :c:func:`PyArg_UnpackTuple`,
620simply write out all the arguments, specifying each as an ``object``. You
621may specify the ``type`` argument to cast the type as appropriate. All
622arguments should be marked positional-only (add a ``/`` on a line by itself
623after the last argument).
624
625Currently the generated code will use :c:func:`PyArg_ParseTuple`, but this
626will change soon.
627
Larry Hastings78cf85c2014-01-04 12:44:57 -0800628Optional Groups
629---------------
630
631Some legacy functions have a tricky approach to parsing their arguments:
632they count the number of positional arguments, then use a ``switch`` statement
Larry Hastings6d2ea212014-01-05 02:50:45 -0800633to call one of several different :c:func:`PyArg_ParseTuple` calls depending on
Larry Hastings78cf85c2014-01-04 12:44:57 -0800634how many positional arguments there are. (These functions cannot accept
635keyword-only arguments.) This approach was used to simulate optional
Larry Hastings6d2ea212014-01-05 02:50:45 -0800636arguments back before :c:func:`PyArg_ParseTupleAndKeywords` was created.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800637
Larry Hastings6d2ea212014-01-05 02:50:45 -0800638While functions using this approach can often be converted to
639use :c:func:`PyArg_ParseTupleAndKeywords`, optional arguments, and default values,
640it's not always possible. Some of these legacy functions have
641behaviors :c:func:`PyArg_ParseTupleAndKeywords` doesn't directly support.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800642The most obvious example is the builtin function ``range()``, which has
643an optional argument on the *left* side of its required argument!
644Another example is ``curses.window.addch()``, which has a group of two
645arguments that must always be specified together. (The arguments are
646called ``x`` and ``y``; if you call the function passing in ``x``,
Martin Panter357ed2e2016-11-21 00:15:20 +0000647you must also pass in ``y``—and if you don't pass in ``x`` you may not
Larry Hastings78cf85c2014-01-04 12:44:57 -0800648pass in ``y`` either.)
649
Larry Hastings6d2ea212014-01-05 02:50:45 -0800650In any case, the goal of Argument Clinic is to support argument parsing
651for all existing CPython builtins without changing their semantics.
652Therefore Argument Clinic supports
653this alternate approach to parsing, using what are called *optional groups*.
654Optional groups are groups of arguments that must all be passed in together.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800655They can be to the left or the right of the required arguments. They
656can *only* be used with positional-only parameters.
657
Larry Hastings42d9e1b2014-01-22 05:49:11 -0800658.. note:: Optional groups are *only* intended for use when converting
659 functions that make multiple calls to :c:func:`PyArg_ParseTuple`!
660 Functions that use *any* other approach for parsing arguments
661 should *almost never* be converted to Argument Clinic using
662 optional groups. Functions using optional groups currently
Martin Panterb4a2b362016-08-12 12:02:03 +0000663 cannot have accurate signatures in Python, because Python just
Larry Hastings42d9e1b2014-01-22 05:49:11 -0800664 doesn't understand the concept. Please avoid using optional
665 groups wherever possible.
666
Larry Hastings78cf85c2014-01-04 12:44:57 -0800667To specify an optional group, add a ``[`` on a line by itself before
Larry Hastings6d2ea212014-01-05 02:50:45 -0800668the parameters you wish to group together, and a ``]`` on a line by itself
669after these parameters. As an example, here's how ``curses.window.addch``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800670uses optional groups to make the first two parameters and the last
671parameter optional::
672
Larry Hastings61272b72014-01-07 12:41:53 -0800673 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800674
675 curses.window.addch
676
677 [
678 x: int
679 X-coordinate.
680 y: int
681 Y-coordinate.
682 ]
683
684 ch: object
685 Character to add.
686
687 [
688 attr: long
689 Attributes for the character.
690 ]
691 /
692
693 ...
694
695
696Notes:
697
698* For every optional group, one additional parameter will be passed into the
Larry Hastings6d2ea212014-01-05 02:50:45 -0800699 impl function representing the group. The parameter will be an int named
700 ``group_{direction}_{number}``,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800701 where ``{direction}`` is either ``right`` or ``left`` depending on whether the group
702 is before or after the required parameters, and ``{number}`` is a monotonically
703 increasing number (starting at 1) indicating how far away the group is from
704 the required parameters. When the impl is called, this parameter will be set
705 to zero if this group was unused, and set to non-zero if this group was used.
706 (By used or unused, I mean whether or not the parameters received arguments
707 in this invocation.)
708
709* If there are no required arguments, the optional groups will behave
Larry Hastings6d2ea212014-01-05 02:50:45 -0800710 as if they're to the right of the required arguments.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800711
712* In the case of ambiguity, the argument parsing code
713 favors parameters on the left (before the required parameters).
714
Larry Hastings6d2ea212014-01-05 02:50:45 -0800715* Optional groups can only contain positional-only parameters.
716
Larry Hastings78cf85c2014-01-04 12:44:57 -0800717* Optional groups are *only* intended for legacy code. Please do not
718 use optional groups for new code.
719
720
721Using real Argument Clinic converters, instead of "legacy converters"
722---------------------------------------------------------------------
723
724To save time, and to minimize how much you need to learn
725to achieve your first port to Argument Clinic, the walkthrough above tells
Larry Hastings6d2ea212014-01-05 02:50:45 -0800726you to use "legacy converters". "Legacy converters" are a convenience,
Larry Hastings78cf85c2014-01-04 12:44:57 -0800727designed explicitly to make porting existing code to Argument Clinic
Larry Hastings4a55fc52014-01-12 11:09:57 -0800728easier. And to be clear, their use is acceptable when porting code for
729Python 3.4.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800730
731However, in the long term we probably want all our blocks to
732use Argument Clinic's real syntax for converters. Why? A couple
733reasons:
734
735* The proper converters are far easier to read and clearer in their intent.
736* There are some format units that are unsupported as "legacy converters",
737 because they require arguments, and the legacy converter syntax doesn't
738 support specifying arguments.
739* In the future we may have a new argument parsing library that isn't
Larry Hastings6d2ea212014-01-05 02:50:45 -0800740 restricted to what :c:func:`PyArg_ParseTuple` supports; this flexibility
741 won't be available to parameters using legacy converters.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800742
Larry Hastings4a55fc52014-01-12 11:09:57 -0800743Therefore, if you don't mind a little extra effort, please use the normal
744converters instead of legacy converters.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800745
746In a nutshell, the syntax for Argument Clinic (non-legacy) converters
747looks like a Python function call. However, if there are no explicit
748arguments to the function (all functions take their default values),
749you may omit the parentheses. Thus ``bool`` and ``bool()`` are exactly
Larry Hastings6d2ea212014-01-05 02:50:45 -0800750the same converters.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800751
Larry Hastings6d2ea212014-01-05 02:50:45 -0800752All arguments to Argument Clinic converters are keyword-only.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800753All Argument Clinic converters accept the following arguments:
754
Larry Hastings2a727912014-01-16 11:32:01 -0800755 ``c_default``
756 The default value for this parameter when defined in C.
757 Specifically, this will be the initializer for the variable declared
758 in the "parse function". See :ref:`the section on default values <default_values>`
759 for how to use this.
760 Specified as a string.
Larry Hastings4a55fc52014-01-12 11:09:57 -0800761
Larry Hastings2a727912014-01-16 11:32:01 -0800762 ``annotation``
763 The annotation value for this parameter. Not currently supported,
764 because PEP 8 mandates that the Python library may not use
765 annotations.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800766
Larry Hastings2a727912014-01-16 11:32:01 -0800767In addition, some converters accept additional arguments. Here is a list
768of these arguments, along with their meanings:
Larry Hastings78cf85c2014-01-04 12:44:57 -0800769
Larry Hastings38337d12015-05-07 23:30:09 -0700770 ``accept``
771 A set of Python types (and possibly pseudo-types);
772 this restricts the allowable Python argument to values of these types.
773 (This is not a general-purpose facility; as a rule it only supports
774 specific lists of types as shown in the legacy converter table.)
775
776 To accept ``None``, add ``NoneType`` to this set.
777
Larry Hastings2a727912014-01-16 11:32:01 -0800778 ``bitwise``
779 Only supported for unsigned integers. The native integer value of this
780 Python argument will be written to the parameter without any range checking,
781 even for negative values.
Larry Hastings4a55fc52014-01-12 11:09:57 -0800782
Larry Hastings2a727912014-01-16 11:32:01 -0800783 ``converter``
784 Only supported by the ``object`` converter. Specifies the name of a
785 :ref:`C "converter function" <o_ampersand>`
786 to use to convert this object to a native type.
787
788 ``encoding``
789 Only supported for strings. Specifies the encoding to use when converting
790 this string from a Python str (Unicode) value into a C ``char *`` value.
791
Larry Hastings2a727912014-01-16 11:32:01 -0800792
793 ``subclass_of``
794 Only supported for the ``object`` converter. Requires that the Python
795 value be a subclass of a Python type, as expressed in C.
796
Larry Hastings38337d12015-05-07 23:30:09 -0700797 ``type``
798 Only supported for the ``object`` and ``self`` converters. Specifies
Larry Hastings2a727912014-01-16 11:32:01 -0800799 the C type that will be used to declare the variable. Default value is
800 ``"PyObject *"``.
801
Larry Hastings2a727912014-01-16 11:32:01 -0800802 ``zeroes``
803 Only supported for strings. If true, embedded NUL bytes (``'\\0'``) are
Larry Hastings38337d12015-05-07 23:30:09 -0700804 permitted inside the value. The length of the string will be passed in
805 to the impl function, just after the string parameter, as a parameter named
806 ``<parameter_name>_length``.
Larry Hastings2a727912014-01-16 11:32:01 -0800807
808Please note, not every possible combination of arguments will work.
Larry Hastings38337d12015-05-07 23:30:09 -0700809Usually these arguments are implemented by specific ``PyArg_ParseTuple``
Larry Hastings2a727912014-01-16 11:32:01 -0800810*format units*, with specific behavior. For example, currently you cannot
Larry Hastings38337d12015-05-07 23:30:09 -0700811call ``unsigned_short`` without also specifying ``bitwise=True``.
812Although it's perfectly reasonable to think this would work, these semantics don't
Larry Hastings2a727912014-01-16 11:32:01 -0800813map to any existing format unit. So Argument Clinic doesn't support it. (Or, at
814least, not yet.)
Larry Hastings78cf85c2014-01-04 12:44:57 -0800815
816Below is a table showing the mapping of legacy converters into real
817Argument Clinic converters. On the left is the legacy converter,
818on the right is the text you'd replace it with.
819
820========= =================================================================================
Larry Hastingsb7ccb202014-01-18 23:50:21 -0800821``'B'`` ``unsigned_char(bitwise=True)``
822``'b'`` ``unsigned_char``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800823``'c'`` ``char``
Larry Hastings38337d12015-05-07 23:30:09 -0700824``'C'`` ``int(accept={str})``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800825``'d'`` ``double``
826``'D'`` ``Py_complex``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800827``'es'`` ``str(encoding='name_of_encoding')``
Larry Hastings38337d12015-05-07 23:30:09 -0700828``'es#'`` ``str(encoding='name_of_encoding', zeroes=True)``
829``'et'`` ``str(encoding='name_of_encoding', accept={bytes, bytearray, str})``
830``'et#'`` ``str(encoding='name_of_encoding', accept={bytes, bytearray, str}, zeroes=True)``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800831``'f'`` ``float``
832``'h'`` ``short``
Larry Hastings4a55fc52014-01-12 11:09:57 -0800833``'H'`` ``unsigned_short(bitwise=True)``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800834``'i'`` ``int``
Larry Hastings4a55fc52014-01-12 11:09:57 -0800835``'I'`` ``unsigned_int(bitwise=True)``
836``'k'`` ``unsigned_long(bitwise=True)``
Benjamin Petersoncc854492016-09-08 09:29:11 -0700837``'K'`` ``unsigned_long_long(bitwise=True)``
Tal Einat97fceee2015-05-16 14:12:15 +0300838``'l'`` ``long``
Benjamin Petersoncc854492016-09-08 09:29:11 -0700839``'L'`` ``long long``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800840``'n'`` ``Py_ssize_t``
Larry Hastings38337d12015-05-07 23:30:09 -0700841``'O'`` ``object``
Larry Hastings77561cc2014-01-07 12:13:13 -0800842``'O!'`` ``object(subclass_of='&PySomething_Type')``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800843``'O&'`` ``object(converter='name_of_c_function')``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800844``'p'`` ``bool``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800845``'S'`` ``PyBytesObject``
846``'s'`` ``str``
Larry Hastings38337d12015-05-07 23:30:09 -0700847``'s#'`` ``str(zeroes=True)``
848``'s*'`` ``Py_buffer(accept={buffer, str})``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800849``'U'`` ``unicode``
Larry Hastings38337d12015-05-07 23:30:09 -0700850``'u'`` ``Py_UNICODE``
851``'u#'`` ``Py_UNICODE(zeroes=True)``
852``'w*'`` ``Py_buffer(accept={rwbuffer})``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800853``'Y'`` ``PyByteArrayObject``
Larry Hastings38337d12015-05-07 23:30:09 -0700854``'y'`` ``str(accept={bytes})``
855``'y#'`` ``str(accept={robuffer}, zeroes=True)``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800856``'y*'`` ``Py_buffer``
Larry Hastings38337d12015-05-07 23:30:09 -0700857``'Z'`` ``Py_UNICODE(accept={str, NoneType})``
858``'Z#'`` ``Py_UNICODE(accept={str, NoneType}, zeroes=True)``
859``'z'`` ``str(accept={str, NoneType})``
860``'z#'`` ``str(accept={str, NoneType}, zeroes=True)``
861``'z*'`` ``Py_buffer(accept={buffer, str, NoneType})``
Larry Hastings78cf85c2014-01-04 12:44:57 -0800862========= =================================================================================
863
864As an example, here's our sample ``pickle.Pickler.dump`` using the proper
865converter::
866
Larry Hastings61272b72014-01-07 12:41:53 -0800867 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -0800868 pickle.Pickler.dump
869
870 obj: object
871 The object to be pickled.
872 /
873
874 Write a pickled representation of obj to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -0800875 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -0800876
877Argument Clinic will show you all the converters it has
878available. For each converter it'll show you all the parameters
879it accepts, along with the default value for each parameter.
880Just run ``Tools/clinic/clinic.py --converters`` to see the full list.
881
Larry Hastings4a55fc52014-01-12 11:09:57 -0800882Py_buffer
883---------
884
885When using the ``Py_buffer`` converter
Larry Hastings0191be32014-01-12 13:57:36 -0800886(or the ``'s*'``, ``'w*'``, ``'*y'``, or ``'z*'`` legacy converters),
887you *must* not call :c:func:`PyBuffer_Release` on the provided buffer.
888Argument Clinic generates code that does it for you (in the parsing function).
889
Larry Hastings4a55fc52014-01-12 11:09:57 -0800890
Larry Hastings78cf85c2014-01-04 12:44:57 -0800891
892Advanced converters
893-------------------
894
Donald Stufft8b852f12014-05-20 12:58:38 -0400895Remember those format units you skipped for your first
Larry Hastings78cf85c2014-01-04 12:44:57 -0800896time because they were advanced? Here's how to handle those too.
897
Martin Panter357ed2e2016-11-21 00:15:20 +0000898The trick is, all those format units take argumentseither
Larry Hastings78cf85c2014-01-04 12:44:57 -0800899conversion functions, or types, or strings specifying an encoding.
900(But "legacy converters" don't support arguments. That's why we
901skipped them for your first function.) The argument you specified
902to the format unit is now an argument to the converter; this
Larry Hastings77561cc2014-01-07 12:13:13 -0800903argument is either ``converter`` (for ``O&``), ``subclass_of`` (for ``O!``),
Larry Hastings78cf85c2014-01-04 12:44:57 -0800904or ``encoding`` (for all the format units that start with ``e``).
905
Larry Hastings77561cc2014-01-07 12:13:13 -0800906When using ``subclass_of``, you may also want to use the other
907custom argument for ``object()``: ``type``, which lets you set the type
908actually used for the parameter. For example, if you want to ensure
909that the object is a subclass of ``PyUnicode_Type``, you probably want
910to use the converter ``object(type='PyUnicodeObject *', subclass_of='&PyUnicode_Type')``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800911
Larry Hastings77561cc2014-01-07 12:13:13 -0800912One possible problem with using Argument Clinic: it takes away some possible
913flexibility for the format units starting with ``e``. When writing a
914``PyArg_Parse`` call by hand, you could theoretically decide at runtime what
Larry Hastings6d2ea212014-01-05 02:50:45 -0800915encoding string to pass in to :c:func:`PyArg_ParseTuple`. But now this string must
Larry Hastings77561cc2014-01-07 12:13:13 -0800916be hard-coded at Argument-Clinic-preprocessing-time. This limitation is deliberate;
917it made supporting this format unit much easier, and may allow for future optimizations.
918This restriction doesn't seem unreasonable; CPython itself always passes in static
Larry Hastings6d2ea212014-01-05 02:50:45 -0800919hard-coded encoding strings for parameters whose format units start with ``e``.
Larry Hastings78cf85c2014-01-04 12:44:57 -0800920
921
Larry Hastings2a727912014-01-16 11:32:01 -0800922.. _default_values:
923
924Parameter default values
925------------------------
926
927Default values for parameters can be any of a number of values.
928At their simplest, they can be string, int, or float literals::
929
930 foo: str = "abc"
931 bar: int = 123
932 bat: float = 45.6
933
934They can also use any of Python's built-in constants::
935
936 yep: bool = True
937 nope: bool = False
938 nada: object = None
939
940There's also special support for a default value of ``NULL``, and
941for simple expressions, documented in the following sections.
942
943
944The ``NULL`` default value
945--------------------------
946
947For string and object parameters, you can set them to ``None`` to indicate
948that there's no default. However, that means the C variable will be
949initialized to ``Py_None``. For convenience's sakes, there's a special
950value called ``NULL`` for just this reason: from Python's perspective it
951behaves like a default value of ``None``, but the C variable is initialized
952with ``NULL``.
953
954Expressions specified as default values
955---------------------------------------
956
957The default value for a parameter can be more than just a literal value.
958It can be an entire expression, using math operators and looking up attributes
959on objects. However, this support isn't exactly simple, because of some
960non-obvious semantics.
961
962Consider the following example::
963
964 foo: Py_ssize_t = sys.maxsize - 1
965
966``sys.maxsize`` can have different values on different platforms. Therefore
967Argument Clinic can't simply evaluate that expression locally and hard-code it
968in C. So it stores the default in such a way that it will get evaluated at
969runtime, when the user asks for the function's signature.
970
971What namespace is available when the expression is evaluated? It's evaluated
972in the context of the module the builtin came from. So, if your module has an
973attribute called "``max_widgets``", you may simply use it::
974
975 foo: Py_ssize_t = max_widgets
976
977If the symbol isn't found in the current module, it fails over to looking in
978``sys.modules``. That's how it can find ``sys.maxsize`` for example. (Since you
979don't know in advance what modules the user will load into their interpreter,
980it's best to restrict yourself to modules that are preloaded by Python itself.)
981
982Evaluating default values only at runtime means Argument Clinic can't compute
983the correct equivalent C default value. So you need to tell it explicitly.
984When you use an expression, you must also specify the equivalent expression
985in C, using the ``c_default`` parameter to the converter::
986
987 foo: Py_ssize_t(c_default="PY_SSIZE_T_MAX - 1") = sys.maxsize - 1
988
989Another complication: Argument Clinic can't know in advance whether or not the
990expression you supply is valid. It parses it to make sure it looks legal, but
991it can't *actually* know. You must be very careful when using expressions to
992specify values that are guaranteed to be valid at runtime!
993
994Finally, because expressions must be representable as static C values, there
995are many restrictions on legal expressions. Here's a list of Python features
996you're not permitted to use:
997
998* Function calls.
999* Inline if statements (``3 if foo else 5``).
1000* Automatic sequence unpacking (``*[1, 2, 3]``).
1001* List/set/dict comprehensions and generator expressions.
1002* Tuple/list/set/dict literals.
1003
1004
1005
Larry Hastings78cf85c2014-01-04 12:44:57 -08001006Using a return converter
1007------------------------
1008
1009By default the impl function Argument Clinic generates for you returns ``PyObject *``.
1010But your C function often computes some C type, then converts it into the ``PyObject *``
1011at the last moment. Argument Clinic handles converting your inputs from Python types
Martin Panter357ed2e2016-11-21 00:15:20 +00001012into native C typeswhy not have it convert your return value from a native C type
Larry Hastings78cf85c2014-01-04 12:44:57 -08001013into a Python type too?
1014
1015That's what a "return converter" does. It changes your impl function to return
1016some C type, then adds code to the generated (non-impl) function to handle converting
1017that value into the appropriate ``PyObject *``.
1018
1019The syntax for return converters is similar to that of parameter converters.
1020You specify the return converter like it was a return annotation on the
1021function itself. Return converters behave much the same as parameter converters;
1022they take arguments, the arguments are all keyword-only, and if you're not changing
1023any of the default arguments you can omit the parentheses.
1024
1025(If you use both ``"as"`` *and* a return converter for your function,
1026the ``"as"`` should come before the return converter.)
1027
1028There's one additional complication when using return converters: how do you
Donald Stufft8b852f12014-05-20 12:58:38 -04001029indicate an error has occurred? Normally, a function returns a valid (non-``NULL``)
Larry Hastings78cf85c2014-01-04 12:44:57 -08001030pointer for success, and ``NULL`` for failure. But if you use an integer return converter,
1031all integers are valid. How can Argument Clinic detect an error? Its solution: each return
1032converter implicitly looks for a special value that indicates an error. If you return
1033that value, and an error has been set (``PyErr_Occurred()`` returns a true
Donald Stufft8b852f12014-05-20 12:58:38 -04001034value), then the generated code will propagate the error. Otherwise it will
Larry Hastings78cf85c2014-01-04 12:44:57 -08001035encode the value you return like normal.
1036
Martin Pantercfa9bad2016-12-10 04:10:45 +00001037Currently Argument Clinic supports only a few return converters:
1038
1039.. code-block:: none
Larry Hastings78cf85c2014-01-04 12:44:57 -08001040
Larry Hastings4a55fc52014-01-12 11:09:57 -08001041 bool
Larry Hastings78cf85c2014-01-04 12:44:57 -08001042 int
Larry Hastings4a55fc52014-01-12 11:09:57 -08001043 unsigned int
Larry Hastings78cf85c2014-01-04 12:44:57 -08001044 long
Larry Hastings4a55fc52014-01-12 11:09:57 -08001045 unsigned int
1046 size_t
Larry Hastings78cf85c2014-01-04 12:44:57 -08001047 Py_ssize_t
Larry Hastings4a55fc52014-01-12 11:09:57 -08001048 float
1049 double
Larry Hastings78cf85c2014-01-04 12:44:57 -08001050 DecodeFSDefault
1051
1052None of these take parameters. For the first three, return -1 to indicate
Serhiy Storchaka84b8e922017-03-30 10:01:03 +03001053error. For ``DecodeFSDefault``, the return type is ``const char *``; return a NULL
Larry Hastings78cf85c2014-01-04 12:44:57 -08001054pointer to indicate an error.
1055
Larry Hastings4a55fc52014-01-12 11:09:57 -08001056(There's also an experimental ``NoneType`` converter, which lets you
1057return ``Py_None`` on success or ``NULL`` on failure, without having
1058to increment the reference count on ``Py_None``. I'm not sure it adds
1059enough clarity to be worth using.)
1060
Larry Hastings6d2ea212014-01-05 02:50:45 -08001061To see all the return converters Argument Clinic supports, along with
1062their parameters (if any),
1063just run ``Tools/clinic/clinic.py --converters`` for the full list.
1064
1065
Larry Hastings4a714d42014-01-14 22:22:41 -08001066Cloning existing functions
1067--------------------------
1068
1069If you have a number of functions that look similar, you may be able to
1070use Clinic's "clone" feature. When you clone an existing function,
1071you reuse:
1072
1073* its parameters, including
1074
1075 * their names,
1076
1077 * their converters, with all parameters,
1078
1079 * their default values,
1080
1081 * their per-parameter docstrings,
1082
1083 * their *kind* (whether they're positional only,
1084 positional or keyword, or keyword only), and
1085
1086* its return converter.
1087
1088The only thing not copied from the original function is its docstring;
1089the syntax allows you to specify a new docstring.
1090
1091Here's the syntax for cloning a function::
1092
1093 /*[clinic input]
1094 module.class.new_function [as c_basename] = module.class.existing_function
1095
1096 Docstring for new_function goes here.
1097 [clinic start generated code]*/
1098
1099(The functions can be in different modules or classes. I wrote
1100``module.class`` in the sample just to illustrate that you must
1101use the full path to *both* functions.)
1102
1103Sorry, there's no syntax for partially-cloning a function, or cloning a function
1104then modifying it. Cloning is an all-or nothing proposition.
1105
1106Also, the function you are cloning from must have been previously defined
1107in the current file.
1108
Larry Hastings78cf85c2014-01-04 12:44:57 -08001109Calling Python code
1110-------------------
1111
1112The rest of the advanced topics require you to write Python code
Larry Hastings6d2ea212014-01-05 02:50:45 -08001113which lives inside your C file and modifies Argument Clinic's
1114runtime state. This is simple: you simply define a Python block.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001115
1116A Python block uses different delimiter lines than an Argument
1117Clinic function block. It looks like this::
1118
Larry Hastings61272b72014-01-07 12:41:53 -08001119 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001120 # python code goes here
Larry Hastings61272b72014-01-07 12:41:53 -08001121 [python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001122
1123All the code inside the Python block is executed at the
1124time it's parsed. All text written to stdout inside the block
1125is redirected into the "output" after the block.
1126
1127As an example, here's a Python block that adds a static integer
1128variable to the C code::
1129
Larry Hastings61272b72014-01-07 12:41:53 -08001130 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001131 print('static int __ignored_unused_variable__ = 0;')
Larry Hastings61272b72014-01-07 12:41:53 -08001132 [python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001133 static int __ignored_unused_variable__ = 0;
1134 /*[python checksum:...]*/
1135
1136
1137Using a "self converter"
1138------------------------
1139
1140Argument Clinic automatically adds a "self" parameter for you
Larry Hastings0e254102014-01-26 00:42:02 -08001141using a default converter. It automatically sets the ``type``
1142of this parameter to the "pointer to an instance" you specified
1143when you declared the type. However, you can override
Larry Hastings78cf85c2014-01-04 12:44:57 -08001144Argument Clinic's converter and specify one yourself.
1145Just add your own ``self`` parameter as the first parameter in a
1146block, and ensure that its converter is an instance of
1147``self_converter`` or a subclass thereof.
1148
Larry Hastings0e254102014-01-26 00:42:02 -08001149What's the point? This lets you override the type of ``self``,
1150or give it a different default name.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001151
1152How do you specify the custom type you want to cast ``self`` to?
1153If you only have one or two functions with the same type for ``self``,
1154you can directly use Argument Clinic's existing ``self`` converter,
1155passing in the type you want to use as the ``type`` parameter::
1156
Larry Hastings61272b72014-01-07 12:41:53 -08001157 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001158
1159 _pickle.Pickler.dump
1160
1161 self: self(type="PicklerObject *")
1162 obj: object
1163 /
1164
1165 Write a pickled representation of the given object to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -08001166 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001167
1168On the other hand, if you have a lot of functions that will use the same
1169type for ``self``, it's best to create your own converter, subclassing
1170``self_converter`` but overwriting the ``type`` member::
1171
Zachary Warec1cb2272014-01-09 21:41:23 -06001172 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001173 class PicklerObject_converter(self_converter):
1174 type = "PicklerObject *"
Zachary Warec1cb2272014-01-09 21:41:23 -06001175 [python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001176
Larry Hastings61272b72014-01-07 12:41:53 -08001177 /*[clinic input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001178
1179 _pickle.Pickler.dump
1180
1181 self: PicklerObject
1182 obj: object
1183 /
1184
1185 Write a pickled representation of the given object to the open file.
Larry Hastings61272b72014-01-07 12:41:53 -08001186 [clinic start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001187
1188
1189
1190Writing a custom converter
1191--------------------------
1192
1193As we hinted at in the previous section... you can write your own converters!
1194A converter is simply a Python class that inherits from ``CConverter``.
1195The main purpose of a custom converter is if you have a parameter using
Martin Panter357ed2e2016-11-21 00:15:20 +00001196the ``O&`` format unitparsing this parameter means calling
Larry Hastings6d2ea212014-01-05 02:50:45 -08001197a :c:func:`PyArg_ParseTuple` "converter function".
Larry Hastings78cf85c2014-01-04 12:44:57 -08001198
1199Your converter class should be named ``*something*_converter``.
1200If the name follows this convention, then your converter class
1201will be automatically registered with Argument Clinic; its name
1202will be the name of your class with the ``_converter`` suffix
Larry Hastings6d2ea212014-01-05 02:50:45 -08001203stripped off. (This is accomplished with a metaclass.)
Larry Hastings78cf85c2014-01-04 12:44:57 -08001204
1205You shouldn't subclass ``CConverter.__init__``. Instead, you should
1206write a ``converter_init()`` function. ``converter_init()``
1207always accepts a ``self`` parameter; after that, all additional
1208parameters *must* be keyword-only. Any arguments passed in to
1209the converter in Argument Clinic will be passed along to your
1210``converter_init()``.
1211
1212There are some additional members of ``CConverter`` you may wish
1213to specify in your subclass. Here's the current list:
1214
1215``type``
1216 The C type to use for this variable.
1217 ``type`` should be a Python string specifying the type, e.g. ``int``.
1218 If this is a pointer type, the type string should end with ``' *'``.
1219
1220``default``
1221 The Python default value for this parameter, as a Python value.
1222 Or the magic value ``unspecified`` if there is no default.
1223
Larry Hastings78cf85c2014-01-04 12:44:57 -08001224``py_default``
1225 ``default`` as it should appear in Python code,
1226 as a string.
1227 Or ``None`` if there is no default.
1228
1229``c_default``
1230 ``default`` as it should appear in C code,
1231 as a string.
1232 Or ``None`` if there is no default.
1233
1234``c_ignored_default``
1235 The default value used to initialize the C variable when
1236 there is no default, but not specifying a default may
Larry Hastings6d2ea212014-01-05 02:50:45 -08001237 result in an "uninitialized variable" warning. This can
Martin Panter357ed2e2016-11-21 00:15:20 +00001238 easily happen when using option groupsalthough
Larry Hastings6d2ea212014-01-05 02:50:45 -08001239 properly-written code will never actually use this value,
1240 the variable does get passed in to the impl, and the
1241 C compiler will complain about the "use" of the
1242 uninitialized value. This value should always be a
1243 non-empty string.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001244
1245``converter``
1246 The name of the C converter function, as a string.
1247
1248``impl_by_reference``
1249 A boolean value. If true,
1250 Argument Clinic will add a ``&`` in front of the name of
1251 the variable when passing it into the impl function.
1252
1253``parse_by_reference``
1254 A boolean value. If true,
1255 Argument Clinic will add a ``&`` in front of the name of
Larry Hastings6d2ea212014-01-05 02:50:45 -08001256 the variable when passing it into :c:func:`PyArg_ParseTuple`.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001257
1258
1259Here's the simplest example of a custom converter, from ``Modules/zlibmodule.c``::
1260
Larry Hastings61272b72014-01-07 12:41:53 -08001261 /*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001262
Martin Panter84544c12016-07-23 03:02:07 +00001263 class ssize_t_converter(CConverter):
1264 type = 'Py_ssize_t'
1265 converter = 'ssize_t_converter'
Larry Hastings78cf85c2014-01-04 12:44:57 -08001266
Larry Hastings61272b72014-01-07 12:41:53 -08001267 [python start generated code]*/
Martin Pantere99e9772015-11-20 08:13:35 +00001268 /*[python end generated code: output=da39a3ee5e6b4b0d input=35521e4e733823c7]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001269
Martin Panter84544c12016-07-23 03:02:07 +00001270This block adds a converter to Argument Clinic named ``ssize_t``. Parameters
1271declared as ``ssize_t`` will be declared as type ``Py_ssize_t``, and will
Martin Pantere99e9772015-11-20 08:13:35 +00001272be parsed by the ``'O&'`` format unit, which will call the
Martin Panter84544c12016-07-23 03:02:07 +00001273``ssize_t_converter`` converter function. ``ssize_t`` variables
Martin Pantere99e9772015-11-20 08:13:35 +00001274automatically support default values.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001275
1276More sophisticated custom converters can insert custom C code to
1277handle initialization and cleanup.
1278You can see more examples of custom converters in the CPython
1279source tree; grep the C files for the string ``CConverter``.
1280
1281Writing a custom return converter
1282---------------------------------
1283
1284Writing a custom return converter is much like writing
Larry Hastings6d2ea212014-01-05 02:50:45 -08001285a custom converter. Except it's somewhat simpler, because return
Larry Hastings78cf85c2014-01-04 12:44:57 -08001286converters are themselves much simpler.
1287
1288Return converters must subclass ``CReturnConverter``.
1289There are no examples yet of custom return converters,
1290because they are not widely used yet. If you wish to
1291write your own return converter, please read ``Tools/clinic/clinic.py``,
1292specifically the implementation of ``CReturnConverter`` and
1293all its subclasses.
1294
Larry Hastings4a55fc52014-01-12 11:09:57 -08001295METH_O and METH_NOARGS
1296----------------------------------------------
1297
1298To convert a function using ``METH_O``, make sure the function's
1299single argument is using the ``object`` converter, and mark the
1300arguments as positional-only::
1301
1302 /*[clinic input]
1303 meth_o_sample
1304
1305 argument: object
1306 /
1307 [clinic start generated code]*/
1308
1309
1310To convert a function using ``METH_NOARGS``, just don't specify
1311any arguments.
1312
1313You can still use a self converter, a return converter, and specify
1314a ``type`` argument to the object converter for ``METH_O``.
Larry Hastings78cf85c2014-01-04 12:44:57 -08001315
Larry Hastingsb7ccb202014-01-18 23:50:21 -08001316tp_new and tp_init functions
1317----------------------------------------------
1318
Larry Hastings42d9e1b2014-01-22 05:49:11 -08001319You can convert ``tp_new`` and ``tp_init`` functions. Just name
1320them ``__new__`` or ``__init__`` as appropriate. Notes:
Larry Hastingsb7ccb202014-01-18 23:50:21 -08001321
1322* The function name generated for ``__new__`` doesn't end in ``__new__``
1323 like it would by default. It's just the name of the class, converted
1324 into a valid C identifier.
1325
1326* No ``PyMethodDef`` ``#define`` is generated for these functions.
1327
1328* ``__init__`` functions return ``int``, not ``PyObject *``.
1329
Larry Hastings42d9e1b2014-01-22 05:49:11 -08001330* Use the docstring as the class docstring.
1331
1332* Although ``__new__`` and ``__init__`` functions must always
1333 accept both the ``args`` and ``kwargs`` objects, when converting
1334 you may specify any signature for these functions that you like.
1335 (If your function doesn't support keywords, the parsing function
1336 generated will throw an exception if it receives any.)
Larry Hastingsb7ccb202014-01-18 23:50:21 -08001337
Larry Hastingsbebf7352014-01-17 17:47:17 -08001338Changing and redirecting Clinic's output
1339----------------------------------------
1340
1341It can be inconvenient to have Clinic's output interspersed with
1342your conventional hand-edited C code. Luckily, Clinic is configurable:
1343you can buffer up its output for printing later (or earlier!), or write
1344its output to a separate file. You can also add a prefix or suffix to
1345every line of Clinic's generated output.
1346
1347While changing Clinic's output in this manner can be a boon to readability,
1348it may result in Clinic code using types before they are defined, or
Martin Panterb4a2b362016-08-12 12:02:03 +00001349your code attempting to use Clinic-generated code before it is defined.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001350These problems can be easily solved by rearranging the declarations in your file,
1351or moving where Clinic's generated code goes. (This is why the default behavior
1352of Clinic is to output everything into the current block; while many people
1353consider this hampers readability, it will never require rearranging your
1354code to fix definition-before-use problems.)
1355
1356Let's start with defining some terminology:
1357
1358*field*
1359 A field, in this context, is a subsection of Clinic's output.
1360 For example, the ``#define`` for the ``PyMethodDef`` structure
1361 is a field, called ``methoddef_define``. Clinic has seven
1362 different fields it can output per function definition::
1363
1364 docstring_prototype
1365 docstring_definition
1366 methoddef_define
1367 impl_prototype
1368 parser_prototype
1369 parser_definition
1370 impl_definition
1371
1372 All the names are of the form ``"<a>_<b>"``,
1373 where ``"<a>"`` is the semantic object represented (the parsing function,
1374 the impl function, the docstring, or the methoddef structure) and ``"<b>"``
1375 represents what kind of statement the field is. Field names that end in
1376 ``"_prototype"``
1377 represent forward declarations of that thing, without the actual body/data
1378 of the thing; field names that end in ``"_definition"`` represent the actual
1379 definition of the thing, with the body/data of the thing. (``"methoddef"``
1380 is special, it's the only one that ends with ``"_define"``, representing that
1381 it's a preprocessor #define.)
1382
1383*destination*
1384 A destination is a place Clinic can write output to. There are
1385 five built-in destinations:
1386
1387 ``block``
1388 The default destination: printed in the output section of
1389 the current Clinic block.
1390
1391 ``buffer``
1392 A text buffer where you can save text for later. Text sent
Martin Panterb4a2b362016-08-12 12:02:03 +00001393 here is appended to the end of any existing text. It's an
Larry Hastingsbebf7352014-01-17 17:47:17 -08001394 error to have any text left in the buffer when Clinic finishes
1395 processing a file.
1396
1397 ``file``
1398 A separate "clinic file" that will be created automatically by Clinic.
1399 The filename chosen for the file is ``{basename}.clinic{extension}``,
1400 where ``basename`` and ``extension`` were assigned the output
1401 from ``os.path.splitext()`` run on the current file. (Example:
1402 the ``file`` destination for ``_pickle.c`` would be written to
1403 ``_pickle.clinic.c``.)
1404
1405 **Important: When using a** ``file`` **destination, you**
1406 *must check in* **the generated file!**
1407
1408 ``two-pass``
1409 A buffer like ``buffer``. However, a two-pass buffer can only
gfyoungec19ba22017-06-06 15:23:52 -04001410 be dumped once, and it prints out all text sent to it during
1411 all processing, even from Clinic blocks *after* the dumping point.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001412
1413 ``suppress``
Martin Panter357ed2e2016-11-21 00:15:20 +00001414 The text is suppressed—thrown away.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001415
1416
1417Clinic defines five new directives that let you reconfigure its output.
1418
1419The first new directive is ``dump``::
1420
1421 dump <destination>
1422
1423This dumps the current contents of the named destination into the output of
1424the current block, and empties it. This only works with ``buffer`` and
1425``two-pass`` destinations.
1426
1427The second new directive is ``output``. The most basic form of ``output``
1428is like this::
1429
1430 output <field> <destination>
1431
1432This tells Clinic to output *field* to *destination*. ``output`` also
1433supports a special meta-destination, called ``everything``, which tells
1434Clinic to output *all* fields to that *destination*.
1435
1436``output`` has a number of other functions::
1437
1438 output push
1439 output pop
1440 output preset <preset>
1441
1442
1443``output push`` and ``output pop`` allow you to push and pop
1444configurations on an internal configuration stack, so that you
1445can temporarily modify the output configuration, then easily restore
1446the previous configuration. Simply push before your change to save
1447the current configuration, then pop when you wish to restore the
1448previous configuration.
1449
1450``output preset`` sets Clinic's output to one of several built-in
1451preset configurations, as follows:
1452
Larry Hastings7726ac92014-01-31 22:03:12 -08001453 ``block``
1454 Clinic's original starting configuration. Writes everything
1455 immediately after the input block.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001456
1457 Suppress the ``parser_prototype``
1458 and ``docstring_prototype``, write everything else to ``block``.
1459
1460 ``file``
1461 Designed to write everything to the "clinic file" that it can.
1462 You then ``#include`` this file near the top of your file.
1463 You may need to rearrange your file to make this work, though
1464 usually this just means creating forward declarations for various
1465 ``typedef`` and ``PyTypeObject`` definitions.
1466
1467 Suppress the ``parser_prototype``
1468 and ``docstring_prototype``, write the ``impl_definition`` to
1469 ``block``, and write everything else to ``file``.
1470
Larry Hastings0e254102014-01-26 00:42:02 -08001471 The default filename is ``"{dirname}/clinic/{basename}.h"``.
1472
Larry Hastingsbebf7352014-01-17 17:47:17 -08001473 ``buffer``
gfyoungec19ba22017-06-06 15:23:52 -04001474 Save up most of the output from Clinic, to be written into
Larry Hastingsbebf7352014-01-17 17:47:17 -08001475 your file near the end. For Python files implementing modules
1476 or builtin types, it's recommended that you dump the buffer
1477 just above the static structures for your module or
1478 builtin type; these are normally very near the end. Using
1479 ``buffer`` may require even more editing than ``file``, if
1480 your file has static ``PyMethodDef`` arrays defined in the
1481 middle of the file.
1482
1483 Suppress the ``parser_prototype``, ``impl_prototype``,
1484 and ``docstring_prototype``, write the ``impl_definition`` to
1485 ``block``, and write everything else to ``file``.
1486
1487 ``two-pass``
1488 Similar to the ``buffer`` preset, but writes forward declarations to
1489 the ``two-pass`` buffer, and definitions to the ``buffer``.
1490 This is similar to the ``buffer`` preset, but may require
1491 less editing than ``buffer``. Dump the ``two-pass`` buffer
1492 near the top of your file, and dump the ``buffer`` near
1493 the end just like you would when using the ``buffer`` preset.
1494
1495 Suppresses the ``impl_prototype``, write the ``impl_definition``
1496 to ``block``, write ``docstring_prototype``, ``methoddef_define``,
1497 and ``parser_prototype`` to ``two-pass``, write everything else
1498 to ``buffer``.
1499
1500 ``partial-buffer``
1501 Similar to the ``buffer`` preset, but writes more things to ``block``,
1502 only writing the really big chunks of generated code to ``buffer``.
1503 This avoids the definition-before-use problem of ``buffer`` completely,
1504 at the small cost of having slightly more stuff in the block's output.
1505 Dump the ``buffer`` near the end, just like you would when using
1506 the ``buffer`` preset.
1507
1508 Suppresses the ``impl_prototype``, write the ``docstring_definition``
Berker Peksag315e1042015-05-19 01:36:55 +03001509 and ``parser_definition`` to ``buffer``, write everything else to ``block``.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001510
1511The third new directive is ``destination``::
1512
1513 destination <name> <command> [...]
1514
1515This performs an operation on the destination named ``name``.
1516
1517There are two defined subcommands: ``new`` and ``clear``.
1518
1519The ``new`` subcommand works like this::
1520
1521 destination <name> new <type>
1522
1523This creates a new destination with name ``<name>`` and type ``<type>``.
1524
Larry Hastings0e254102014-01-26 00:42:02 -08001525There are five destination types:
Larry Hastingsbebf7352014-01-17 17:47:17 -08001526
1527 ``suppress``
1528 Throws the text away.
1529
1530 ``block``
1531 Writes the text to the current block. This is what Clinic
1532 originally did.
1533
1534 ``buffer``
1535 A simple text buffer, like the "buffer" builtin destination above.
1536
1537 ``file``
1538 A text file. The file destination takes an extra argument,
1539 a template to use for building the filename, like so:
1540
1541 destination <name> new <type> <file_template>
1542
1543 The template can use three strings internally that will be replaced
1544 by bits of the filename:
1545
Larry Hastings0e254102014-01-26 00:42:02 -08001546 {path}
1547 The full path to the file, including directory and full filename.
1548 {dirname}
1549 The name of the directory the file is in.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001550 {basename}
Larry Hastings0e254102014-01-26 00:42:02 -08001551 Just the name of the file, not including the directory.
1552 {basename_root}
1553 Basename with the extension clipped off
1554 (everything up to but not including the last '.').
1555 {basename_extension}
1556 The last '.' and everything after it. If the basename
1557 does not contain a period, this will be the empty string.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001558
1559 If there are no periods in the filename, {basename} and {filename}
1560 are the same, and {extension} is empty. "{basename}{extension}"
1561 is always exactly the same as "{filename}"."
1562
1563 ``two-pass``
1564 A two-pass buffer, like the "two-pass" builtin destination above.
1565
1566
1567The ``clear`` subcommand works like this::
1568
1569 destination <name> clear
1570
1571It removes all the accumulated text up to this point in the destination.
1572(I don't know what you'd need this for, but I thought maybe it'd be
1573useful while someone's experimenting.)
1574
1575The fourth new directive is ``set``::
1576
1577 set line_prefix "string"
1578 set line_suffix "string"
1579
1580``set`` lets you set two internal variables in Clinic.
1581``line_prefix`` is a string that will be prepended to every line of Clinic's output;
1582``line_suffix`` is a string that will be appended to every line of Clinic's output.
1583
Donald Stufft8b852f12014-05-20 12:58:38 -04001584Both of these support two format strings:
Larry Hastingsbebf7352014-01-17 17:47:17 -08001585
1586 ``{block comment start}``
1587 Turns into the string ``/*``, the start-comment text sequence for C files.
1588
1589 ``{block comment end}``
1590 Turns into the string ``*/``, the end-comment text sequence for C files.
1591
1592The final new directive is one you shouldn't need to use directly,
1593called ``preserve``::
1594
1595 preserve
1596
Martin Pantereb995702016-07-28 01:11:04 +00001597This tells Clinic that the current contents of the output should be kept, unmodified.
Larry Hastingsbebf7352014-01-17 17:47:17 -08001598This is used internally by Clinic when dumping output into ``file`` files; wrapping
1599it in a Clinic block lets Clinic use its existing checksum functionality to ensure
1600the file was not modified by hand before it gets overwritten.
1601
1602
Larry Hastings7726ac92014-01-31 22:03:12 -08001603The #ifdef trick
1604----------------------------------------------
1605
1606If you're converting a function that isn't available on all platforms,
1607there's a trick you can use to make life a little easier. The existing
1608code probably looks like this::
1609
1610 #ifdef HAVE_FUNCTIONNAME
1611 static module_functionname(...)
1612 {
1613 ...
1614 }
1615 #endif /* HAVE_FUNCTIONNAME */
1616
1617And then in the ``PyMethodDef`` structure at the bottom the existing code
Martin Pantercfa9bad2016-12-10 04:10:45 +00001618will have:
1619
1620.. code-block:: none
Larry Hastings7726ac92014-01-31 22:03:12 -08001621
1622 #ifdef HAVE_FUNCTIONNAME
1623 {'functionname', ... },
1624 #endif /* HAVE_FUNCTIONNAME */
1625
1626In this scenario, you should enclose the body of your impl function inside the ``#ifdef``,
1627like so::
1628
1629 #ifdef HAVE_FUNCTIONNAME
1630 /*[clinic input]
1631 module.functionname
1632 ...
1633 [clinic start generated code]*/
1634 static module_functionname(...)
1635 {
1636 ...
1637 }
1638 #endif /* HAVE_FUNCTIONNAME */
1639
1640Then, remove those three lines from the ``PyMethodDef`` structure,
1641replacing them with the macro Argument Clinic generated::
1642
1643 MODULE_FUNCTIONNAME_METHODDEF
1644
1645(You can find the real name for this macro inside the generated code.
1646Or you can calculate it yourself: it's the name of your function as defined
1647on the first line of your block, but with periods changed to underscores,
1648uppercased, and ``"_METHODDEF"`` added to the end.)
1649
1650Perhaps you're wondering: what if ``HAVE_FUNCTIONNAME`` isn't defined?
1651The ``MODULE_FUNCTIONNAME_METHODDEF`` macro won't be defined either!
1652
1653Here's where Argument Clinic gets very clever. It actually detects that the
1654Argument Clinic block might be deactivated by the ``#ifdef``. When that
1655happens, it generates a little extra code that looks like this::
1656
1657 #ifndef MODULE_FUNCTIONNAME_METHODDEF
1658 #define MODULE_FUNCTIONNAME_METHODDEF
1659 #endif /* !defined(MODULE_FUNCTIONNAME_METHODDEF) */
1660
1661That means the macro always works. If the function is defined, this turns
1662into the correct structure, including the trailing comma. If the function is
1663undefined, this turns into nothing.
1664
1665However, this causes one ticklish problem: where should Argument Clinic put this
1666extra code when using the "block" output preset? It can't go in the output block,
Martin Panterb4a2b362016-08-12 12:02:03 +00001667because that could be deactivated by the ``#ifdef``. (That's the whole point!)
Larry Hastings7726ac92014-01-31 22:03:12 -08001668
1669In this situation, Argument Clinic writes the extra code to the "buffer" destination.
Martin Pantercfa9bad2016-12-10 04:10:45 +00001670This may mean that you get a complaint from Argument Clinic:
1671
1672.. code-block:: none
Larry Hastings7726ac92014-01-31 22:03:12 -08001673
1674 Warning in file "Modules/posixmodule.c" on line 12357:
1675 Destination buffer 'buffer' not empty at end of file, emptying.
1676
1677When this happens, just open your file, find the ``dump buffer`` block that
1678Argument Clinic added to your file (it'll be at the very bottom), then
1679move it above the ``PyMethodDef`` structure where that macro is used.
1680
1681
1682
Larry Hastingsbebf7352014-01-17 17:47:17 -08001683Using Argument Clinic in Python files
Larry Hastings78cf85c2014-01-04 12:44:57 -08001684-------------------------------------
1685
1686It's actually possible to use Argument Clinic to preprocess Python files.
1687There's no point to using Argument Clinic blocks, of course, as the output
1688wouldn't make any sense to the Python interpreter. But using Argument Clinic
1689to run Python blocks lets you use Python as a Python preprocessor!
1690
1691Since Python comments are different from C comments, Argument Clinic
Martin Pantercfa9bad2016-12-10 04:10:45 +00001692blocks embedded in Python files look slightly different. They look like this:
1693
1694.. code-block:: python3
Larry Hastings78cf85c2014-01-04 12:44:57 -08001695
Larry Hastings61272b72014-01-07 12:41:53 -08001696 #/*[python input]
Larry Hastings78cf85c2014-01-04 12:44:57 -08001697 #print("def foo(): pass")
Larry Hastings61272b72014-01-07 12:41:53 -08001698 #[python start generated code]*/
Larry Hastings78cf85c2014-01-04 12:44:57 -08001699 def foo(): pass
1700 #/*[python checksum:...]*/