17db96d56Sopenharmony_ci.. highlight:: c
27db96d56Sopenharmony_ci
37db96d56Sopenharmony_ci.. _howto-clinic:
47db96d56Sopenharmony_ci
57db96d56Sopenharmony_ci**********************
67db96d56Sopenharmony_ciArgument Clinic How-To
77db96d56Sopenharmony_ci**********************
87db96d56Sopenharmony_ci
97db96d56Sopenharmony_ci:author: Larry Hastings
107db96d56Sopenharmony_ci
117db96d56Sopenharmony_ci
127db96d56Sopenharmony_ci.. topic:: Abstract
137db96d56Sopenharmony_ci
147db96d56Sopenharmony_ci  Argument Clinic is a preprocessor for CPython C files.
157db96d56Sopenharmony_ci  Its purpose is to automate all the boilerplate involved
167db96d56Sopenharmony_ci  with writing argument parsing code for "builtins".
177db96d56Sopenharmony_ci  This document shows you how to convert your first C
187db96d56Sopenharmony_ci  function to work with Argument Clinic, and then introduces
197db96d56Sopenharmony_ci  some advanced topics on Argument Clinic usage.
207db96d56Sopenharmony_ci
217db96d56Sopenharmony_ci  Currently Argument Clinic is considered internal-only
227db96d56Sopenharmony_ci  for CPython.  Its use is not supported for files outside
237db96d56Sopenharmony_ci  CPython, and no guarantees are made regarding backwards
247db96d56Sopenharmony_ci  compatibility for future versions.  In other words: if you
257db96d56Sopenharmony_ci  maintain an external C extension for CPython, you're welcome
267db96d56Sopenharmony_ci  to experiment with Argument Clinic in your own code.  But the
277db96d56Sopenharmony_ci  version of Argument Clinic that ships with the next version
287db96d56Sopenharmony_ci  of CPython *could* be totally incompatible and break all your code.
297db96d56Sopenharmony_ci
307db96d56Sopenharmony_ciThe Goals Of Argument Clinic
317db96d56Sopenharmony_ci============================
327db96d56Sopenharmony_ci
337db96d56Sopenharmony_ciArgument Clinic's primary goal
347db96d56Sopenharmony_ciis to take over responsibility for all argument parsing code
357db96d56Sopenharmony_ciinside CPython.  This means that, when you convert a function
367db96d56Sopenharmony_cito work with Argument Clinic, that function should no longer
377db96d56Sopenharmony_cido any of its own argument parsing—the code generated by
387db96d56Sopenharmony_ciArgument Clinic should be a "black box" to you, where CPython
397db96d56Sopenharmony_cicalls in at the top, and your code gets called at the bottom,
407db96d56Sopenharmony_ciwith ``PyObject *args`` (and maybe ``PyObject *kwargs``)
417db96d56Sopenharmony_cimagically converted into the C variables and types you need.
427db96d56Sopenharmony_ci
437db96d56Sopenharmony_ciIn order for Argument Clinic to accomplish its primary goal,
447db96d56Sopenharmony_ciit must be easy to use.  Currently, working with CPython's
457db96d56Sopenharmony_ciargument parsing library is a chore, requiring maintaining
467db96d56Sopenharmony_ciredundant information in a surprising number of places.
477db96d56Sopenharmony_ciWhen you use Argument Clinic, you don't have to repeat yourself.
487db96d56Sopenharmony_ci
497db96d56Sopenharmony_ciObviously, no one would want to use Argument Clinic unless
507db96d56Sopenharmony_ciit's solving their problem—and without creating new problems of
517db96d56Sopenharmony_ciits own.
527db96d56Sopenharmony_ciSo it's paramount that Argument Clinic generate correct code.
537db96d56Sopenharmony_ciIt'd be nice if the code was faster, too, but at the very least
547db96d56Sopenharmony_ciit should not introduce a major speed regression.  (Eventually Argument
557db96d56Sopenharmony_ciClinic *should* make a major speedup possible—we could
567db96d56Sopenharmony_cirewrite its code generator to produce tailor-made argument
577db96d56Sopenharmony_ciparsing code, rather than calling the general-purpose CPython
587db96d56Sopenharmony_ciargument parsing library.  That would make for the fastest
597db96d56Sopenharmony_ciargument parsing possible!)
607db96d56Sopenharmony_ci
617db96d56Sopenharmony_ciAdditionally, Argument Clinic must be flexible enough to
627db96d56Sopenharmony_ciwork with any approach to argument parsing.  Python has
637db96d56Sopenharmony_cisome functions with some very strange parsing behaviors;
647db96d56Sopenharmony_ciArgument Clinic's goal is to support all of them.
657db96d56Sopenharmony_ci
667db96d56Sopenharmony_ciFinally, the original motivation for Argument Clinic was
677db96d56Sopenharmony_cito provide introspection "signatures" for CPython builtins.
687db96d56Sopenharmony_ciIt used to be, the introspection query functions would throw
697db96d56Sopenharmony_cian exception if you passed in a builtin.  With Argument
707db96d56Sopenharmony_ciClinic, that's a thing of the past!
717db96d56Sopenharmony_ci
727db96d56Sopenharmony_ciOne idea you should keep in mind, as you work with
737db96d56Sopenharmony_ciArgument Clinic: the more information you give it, the
747db96d56Sopenharmony_cibetter job it'll be able to do.
757db96d56Sopenharmony_ciArgument Clinic is admittedly relatively simple right
767db96d56Sopenharmony_cinow.  But as it evolves it will get more sophisticated,
777db96d56Sopenharmony_ciand it should be able to do many interesting and smart
787db96d56Sopenharmony_cithings with all the information you give it.
797db96d56Sopenharmony_ci
807db96d56Sopenharmony_ci
817db96d56Sopenharmony_ciBasic Concepts And Usage
827db96d56Sopenharmony_ci========================
837db96d56Sopenharmony_ci
847db96d56Sopenharmony_ciArgument Clinic ships with CPython; you'll find it in ``Tools/clinic/clinic.py``.
857db96d56Sopenharmony_ciIf you run that script, specifying a C file as an argument:
867db96d56Sopenharmony_ci
877db96d56Sopenharmony_ci.. code-block:: shell-session
887db96d56Sopenharmony_ci
897db96d56Sopenharmony_ci    $ python3 Tools/clinic/clinic.py foo.c
907db96d56Sopenharmony_ci
917db96d56Sopenharmony_ciArgument Clinic will scan over the file looking for lines that
927db96d56Sopenharmony_cilook exactly like this:
937db96d56Sopenharmony_ci
947db96d56Sopenharmony_ci.. code-block:: none
957db96d56Sopenharmony_ci
967db96d56Sopenharmony_ci    /*[clinic input]
977db96d56Sopenharmony_ci
987db96d56Sopenharmony_ciWhen it finds one, it reads everything up to a line that looks
997db96d56Sopenharmony_ciexactly like this:
1007db96d56Sopenharmony_ci
1017db96d56Sopenharmony_ci.. code-block:: none
1027db96d56Sopenharmony_ci
1037db96d56Sopenharmony_ci    [clinic start generated code]*/
1047db96d56Sopenharmony_ci
1057db96d56Sopenharmony_ciEverything in between these two lines is input for Argument Clinic.
1067db96d56Sopenharmony_ciAll of these lines, including the beginning and ending comment
1077db96d56Sopenharmony_cilines, are collectively called an Argument Clinic "block".
1087db96d56Sopenharmony_ci
1097db96d56Sopenharmony_ciWhen Argument Clinic parses one of these blocks, it
1107db96d56Sopenharmony_cigenerates output.  This output is rewritten into the C file
1117db96d56Sopenharmony_ciimmediately after the block, followed by a comment containing a checksum.
1127db96d56Sopenharmony_ciThe Argument Clinic block now looks like this:
1137db96d56Sopenharmony_ci
1147db96d56Sopenharmony_ci.. code-block:: none
1157db96d56Sopenharmony_ci
1167db96d56Sopenharmony_ci    /*[clinic input]
1177db96d56Sopenharmony_ci    ... clinic input goes here ...
1187db96d56Sopenharmony_ci    [clinic start generated code]*/
1197db96d56Sopenharmony_ci    ... clinic output goes here ...
1207db96d56Sopenharmony_ci    /*[clinic end generated code: checksum=...]*/
1217db96d56Sopenharmony_ci
1227db96d56Sopenharmony_ciIf you run Argument Clinic on the same file a second time, Argument Clinic
1237db96d56Sopenharmony_ciwill discard the old output and write out the new output with a fresh checksum
1247db96d56Sopenharmony_ciline.  However, if the input hasn't changed, the output won't change either.
1257db96d56Sopenharmony_ci
1267db96d56Sopenharmony_ciYou should never modify the output portion of an Argument Clinic block.  Instead,
1277db96d56Sopenharmony_cichange the input until it produces the output you want.  (That's the purpose of the
1287db96d56Sopenharmony_cichecksum—to detect if someone changed the output, as these edits would be lost
1297db96d56Sopenharmony_cithe next time Argument Clinic writes out fresh output.)
1307db96d56Sopenharmony_ci
1317db96d56Sopenharmony_ciFor the sake of clarity, here's the terminology we'll use with Argument Clinic:
1327db96d56Sopenharmony_ci
1337db96d56Sopenharmony_ci* The first line of the comment (``/*[clinic input]``) is the *start line*.
1347db96d56Sopenharmony_ci* The last line of the initial comment (``[clinic start generated code]*/``) is the *end line*.
1357db96d56Sopenharmony_ci* The last line (``/*[clinic end generated code: checksum=...]*/``) is the *checksum line*.
1367db96d56Sopenharmony_ci* In between the start line and the end line is the *input*.
1377db96d56Sopenharmony_ci* In between the end line and the checksum line is the *output*.
1387db96d56Sopenharmony_ci* All the text collectively, from the start line to the checksum line inclusively,
1397db96d56Sopenharmony_ci  is the *block*.  (A block that hasn't been successfully processed by Argument
1407db96d56Sopenharmony_ci  Clinic yet doesn't have output or a checksum line, but it's still considered
1417db96d56Sopenharmony_ci  a block.)
1427db96d56Sopenharmony_ci
1437db96d56Sopenharmony_ci
1447db96d56Sopenharmony_ciConverting Your First Function
1457db96d56Sopenharmony_ci==============================
1467db96d56Sopenharmony_ci
1477db96d56Sopenharmony_ciThe best way to get a sense of how Argument Clinic works is to
1487db96d56Sopenharmony_ciconvert a function to work with it.  Here, then, are the bare
1497db96d56Sopenharmony_ciminimum steps you'd need to follow to convert a function to
1507db96d56Sopenharmony_ciwork with Argument Clinic.  Note that for code you plan to
1517db96d56Sopenharmony_cicheck in to CPython, you really should take the conversion farther,
1527db96d56Sopenharmony_ciusing some of the advanced concepts you'll see later on in
1537db96d56Sopenharmony_cithe document (like "return converters" and "self converters").
1547db96d56Sopenharmony_ciBut we'll keep it simple for this walkthrough so you can learn.
1557db96d56Sopenharmony_ci
1567db96d56Sopenharmony_ciLet's dive in!
1577db96d56Sopenharmony_ci
1587db96d56Sopenharmony_ci0. Make sure you're working with a freshly updated checkout
1597db96d56Sopenharmony_ci   of the CPython trunk.
1607db96d56Sopenharmony_ci
1617db96d56Sopenharmony_ci1. Find a Python builtin that calls either :c:func:`PyArg_ParseTuple`
1627db96d56Sopenharmony_ci   or :c:func:`PyArg_ParseTupleAndKeywords`, and hasn't been converted
1637db96d56Sopenharmony_ci   to work with Argument Clinic yet.
1647db96d56Sopenharmony_ci   For my example I'm using ``_pickle.Pickler.dump()``.
1657db96d56Sopenharmony_ci
1667db96d56Sopenharmony_ci2. If the call to the ``PyArg_Parse`` function uses any of the
1677db96d56Sopenharmony_ci   following format units:
1687db96d56Sopenharmony_ci
1697db96d56Sopenharmony_ci   .. code-block:: none
1707db96d56Sopenharmony_ci
1717db96d56Sopenharmony_ci       O&
1727db96d56Sopenharmony_ci       O!
1737db96d56Sopenharmony_ci       es
1747db96d56Sopenharmony_ci       es#
1757db96d56Sopenharmony_ci       et
1767db96d56Sopenharmony_ci       et#
1777db96d56Sopenharmony_ci
1787db96d56Sopenharmony_ci   or if it has multiple calls to :c:func:`PyArg_ParseTuple`,
1797db96d56Sopenharmony_ci   you should choose a different function.  Argument Clinic *does*
1807db96d56Sopenharmony_ci   support all of these scenarios.  But these are advanced
1817db96d56Sopenharmony_ci   topics—let's do something simpler for your first function.
1827db96d56Sopenharmony_ci
1837db96d56Sopenharmony_ci   Also, if the function has multiple calls to :c:func:`PyArg_ParseTuple`
1847db96d56Sopenharmony_ci   or :c:func:`PyArg_ParseTupleAndKeywords` where it supports different
1857db96d56Sopenharmony_ci   types for the same argument, or if the function uses something besides
1867db96d56Sopenharmony_ci   PyArg_Parse functions to parse its arguments, it probably
1877db96d56Sopenharmony_ci   isn't suitable for conversion to Argument Clinic.  Argument Clinic
1887db96d56Sopenharmony_ci   doesn't support generic functions or polymorphic parameters.
1897db96d56Sopenharmony_ci
1907db96d56Sopenharmony_ci3. Add the following boilerplate above the function, creating our block::
1917db96d56Sopenharmony_ci
1927db96d56Sopenharmony_ci    /*[clinic input]
1937db96d56Sopenharmony_ci    [clinic start generated code]*/
1947db96d56Sopenharmony_ci
1957db96d56Sopenharmony_ci4. Cut the docstring and paste it in between the ``[clinic]`` lines,
1967db96d56Sopenharmony_ci   removing all the junk that makes it a properly quoted C string.
1977db96d56Sopenharmony_ci   When you're done you should have just the text, based at the left
1987db96d56Sopenharmony_ci   margin, with no line wider than 80 characters.
1997db96d56Sopenharmony_ci   (Argument Clinic will preserve indents inside the docstring.)
2007db96d56Sopenharmony_ci
2017db96d56Sopenharmony_ci   If the old docstring had a first line that looked like a function
2027db96d56Sopenharmony_ci   signature, throw that line away.  (The docstring doesn't need it
2037db96d56Sopenharmony_ci   anymore—when you use ``help()`` on your builtin in the future,
2047db96d56Sopenharmony_ci   the first line will be built automatically based on the function's
2057db96d56Sopenharmony_ci   signature.)
2067db96d56Sopenharmony_ci
2077db96d56Sopenharmony_ci   Sample::
2087db96d56Sopenharmony_ci
2097db96d56Sopenharmony_ci    /*[clinic input]
2107db96d56Sopenharmony_ci    Write a pickled representation of obj to the open file.
2117db96d56Sopenharmony_ci    [clinic start generated code]*/
2127db96d56Sopenharmony_ci
2137db96d56Sopenharmony_ci5. If your docstring doesn't have a "summary" line, Argument Clinic will
2147db96d56Sopenharmony_ci   complain.  So let's make sure it has one.  The "summary" line should
2157db96d56Sopenharmony_ci   be a paragraph consisting of a single 80-column line
2167db96d56Sopenharmony_ci   at the beginning of the docstring.
2177db96d56Sopenharmony_ci
2187db96d56Sopenharmony_ci   (Our example docstring consists solely of a summary line, so the sample
2197db96d56Sopenharmony_ci   code doesn't have to change for this step.)
2207db96d56Sopenharmony_ci
2217db96d56Sopenharmony_ci6. Above the docstring, enter the name of the function, followed
2227db96d56Sopenharmony_ci   by a blank line.  This should be the Python name of the function,
2237db96d56Sopenharmony_ci   and should be the full dotted path
2247db96d56Sopenharmony_ci   to the function—it should start with the name of the module,
2257db96d56Sopenharmony_ci   include any sub-modules, and if the function is a method on
2267db96d56Sopenharmony_ci   a class it should include the class name too.
2277db96d56Sopenharmony_ci
2287db96d56Sopenharmony_ci   Sample::
2297db96d56Sopenharmony_ci
2307db96d56Sopenharmony_ci    /*[clinic input]
2317db96d56Sopenharmony_ci    _pickle.Pickler.dump
2327db96d56Sopenharmony_ci
2337db96d56Sopenharmony_ci    Write a pickled representation of obj to the open file.
2347db96d56Sopenharmony_ci    [clinic start generated code]*/
2357db96d56Sopenharmony_ci
2367db96d56Sopenharmony_ci7. If this is the first time that module or class has been used with Argument
2377db96d56Sopenharmony_ci   Clinic in this C file,
2387db96d56Sopenharmony_ci   you must declare the module and/or class.  Proper Argument Clinic hygiene
2397db96d56Sopenharmony_ci   prefers declaring these in a separate block somewhere near the
2407db96d56Sopenharmony_ci   top of the C file, in the same way that include files and statics go at
2417db96d56Sopenharmony_ci   the top.  (In our sample code we'll just show the two blocks next to
2427db96d56Sopenharmony_ci   each other.)
2437db96d56Sopenharmony_ci
2447db96d56Sopenharmony_ci   The name of the class and module should be the same as the one
2457db96d56Sopenharmony_ci   seen by Python.  Check the name defined in the :c:type:`PyModuleDef`
2467db96d56Sopenharmony_ci   or :c:type:`PyTypeObject` as appropriate.
2477db96d56Sopenharmony_ci
2487db96d56Sopenharmony_ci   When you declare a class, you must also specify two aspects of its type
2497db96d56Sopenharmony_ci   in C: the type declaration you'd use for a pointer to an instance of
2507db96d56Sopenharmony_ci   this class, and a pointer to the :c:type:`PyTypeObject` for this class.
2517db96d56Sopenharmony_ci
2527db96d56Sopenharmony_ci   Sample::
2537db96d56Sopenharmony_ci
2547db96d56Sopenharmony_ci       /*[clinic input]
2557db96d56Sopenharmony_ci       module _pickle
2567db96d56Sopenharmony_ci       class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
2577db96d56Sopenharmony_ci       [clinic start generated code]*/
2587db96d56Sopenharmony_ci
2597db96d56Sopenharmony_ci       /*[clinic input]
2607db96d56Sopenharmony_ci       _pickle.Pickler.dump
2617db96d56Sopenharmony_ci
2627db96d56Sopenharmony_ci       Write a pickled representation of obj to the open file.
2637db96d56Sopenharmony_ci       [clinic start generated code]*/
2647db96d56Sopenharmony_ci
2657db96d56Sopenharmony_ci
2667db96d56Sopenharmony_ci
2677db96d56Sopenharmony_ci
2687db96d56Sopenharmony_ci8. Declare each of the parameters to the function.  Each parameter
2697db96d56Sopenharmony_ci   should get its own line.  All the parameter lines should be
2707db96d56Sopenharmony_ci   indented from the function name and the docstring.
2717db96d56Sopenharmony_ci
2727db96d56Sopenharmony_ci   The general form of these parameter lines is as follows:
2737db96d56Sopenharmony_ci
2747db96d56Sopenharmony_ci   .. code-block:: none
2757db96d56Sopenharmony_ci
2767db96d56Sopenharmony_ci       name_of_parameter: converter
2777db96d56Sopenharmony_ci
2787db96d56Sopenharmony_ci   If the parameter has a default value, add that after the
2797db96d56Sopenharmony_ci   converter:
2807db96d56Sopenharmony_ci
2817db96d56Sopenharmony_ci   .. code-block:: none
2827db96d56Sopenharmony_ci
2837db96d56Sopenharmony_ci       name_of_parameter: converter = default_value
2847db96d56Sopenharmony_ci
2857db96d56Sopenharmony_ci   Argument Clinic's support for "default values" is quite sophisticated;
2867db96d56Sopenharmony_ci   please see :ref:`the section below on default values <default_values>`
2877db96d56Sopenharmony_ci   for more information.
2887db96d56Sopenharmony_ci
2897db96d56Sopenharmony_ci   Add a blank line below the parameters.
2907db96d56Sopenharmony_ci
2917db96d56Sopenharmony_ci   What's a "converter"?  It establishes both the type
2927db96d56Sopenharmony_ci   of the variable used in C, and the method to convert the Python
2937db96d56Sopenharmony_ci   value into a C value at runtime.
2947db96d56Sopenharmony_ci   For now you're going to use what's called a "legacy converter"—a
2957db96d56Sopenharmony_ci   convenience syntax intended to make porting old code into Argument
2967db96d56Sopenharmony_ci   Clinic easier.
2977db96d56Sopenharmony_ci
2987db96d56Sopenharmony_ci   For each parameter, copy the "format unit" for that
2997db96d56Sopenharmony_ci   parameter from the ``PyArg_Parse()`` format argument and
3007db96d56Sopenharmony_ci   specify *that* as its converter, as a quoted
3017db96d56Sopenharmony_ci   string.  ("format unit" is the formal name for the one-to-three
3027db96d56Sopenharmony_ci   character substring of the ``format`` parameter that tells
3037db96d56Sopenharmony_ci   the argument parsing function what the type of the variable
3047db96d56Sopenharmony_ci   is and how to convert it.  For more on format units please
3057db96d56Sopenharmony_ci   see :ref:`arg-parsing`.)
3067db96d56Sopenharmony_ci
3077db96d56Sopenharmony_ci   For multicharacter format units like ``z#``, use the
3087db96d56Sopenharmony_ci   entire two-or-three character string.
3097db96d56Sopenharmony_ci
3107db96d56Sopenharmony_ci   Sample::
3117db96d56Sopenharmony_ci
3127db96d56Sopenharmony_ci        /*[clinic input]
3137db96d56Sopenharmony_ci        module _pickle
3147db96d56Sopenharmony_ci        class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
3157db96d56Sopenharmony_ci        [clinic start generated code]*/
3167db96d56Sopenharmony_ci
3177db96d56Sopenharmony_ci        /*[clinic input]
3187db96d56Sopenharmony_ci        _pickle.Pickler.dump
3197db96d56Sopenharmony_ci
3207db96d56Sopenharmony_ci           obj: 'O'
3217db96d56Sopenharmony_ci
3227db96d56Sopenharmony_ci       Write a pickled representation of obj to the open file.
3237db96d56Sopenharmony_ci       [clinic start generated code]*/
3247db96d56Sopenharmony_ci
3257db96d56Sopenharmony_ci9. If your function has ``|`` in the format string, meaning some
3267db96d56Sopenharmony_ci   parameters have default values, you can ignore it.  Argument
3277db96d56Sopenharmony_ci   Clinic infers which parameters are optional based on whether
3287db96d56Sopenharmony_ci   or not they have default values.
3297db96d56Sopenharmony_ci
3307db96d56Sopenharmony_ci   If your function has ``$`` in the format string, meaning it
3317db96d56Sopenharmony_ci   takes keyword-only arguments, specify ``*`` on a line by
3327db96d56Sopenharmony_ci   itself before the first keyword-only argument, indented the
3337db96d56Sopenharmony_ci   same as the parameter lines.
3347db96d56Sopenharmony_ci
3357db96d56Sopenharmony_ci   (``_pickle.Pickler.dump`` has neither, so our sample is unchanged.)
3367db96d56Sopenharmony_ci
3377db96d56Sopenharmony_ci
3387db96d56Sopenharmony_ci10. If the existing C function calls :c:func:`PyArg_ParseTuple`
3397db96d56Sopenharmony_ci    (as opposed to :c:func:`PyArg_ParseTupleAndKeywords`), then all its
3407db96d56Sopenharmony_ci    arguments are positional-only.
3417db96d56Sopenharmony_ci
3427db96d56Sopenharmony_ci    To mark all parameters as positional-only in Argument Clinic,
3437db96d56Sopenharmony_ci    add a ``/`` on a line by itself after the last parameter,
3447db96d56Sopenharmony_ci    indented the same as the parameter lines.
3457db96d56Sopenharmony_ci
3467db96d56Sopenharmony_ci    Currently this is all-or-nothing; either all parameters are
3477db96d56Sopenharmony_ci    positional-only, or none of them are.  (In the future Argument
3487db96d56Sopenharmony_ci    Clinic may relax this restriction.)
3497db96d56Sopenharmony_ci
3507db96d56Sopenharmony_ci    Sample::
3517db96d56Sopenharmony_ci
3527db96d56Sopenharmony_ci        /*[clinic input]
3537db96d56Sopenharmony_ci        module _pickle
3547db96d56Sopenharmony_ci        class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
3557db96d56Sopenharmony_ci        [clinic start generated code]*/
3567db96d56Sopenharmony_ci
3577db96d56Sopenharmony_ci        /*[clinic input]
3587db96d56Sopenharmony_ci        _pickle.Pickler.dump
3597db96d56Sopenharmony_ci
3607db96d56Sopenharmony_ci            obj: 'O'
3617db96d56Sopenharmony_ci            /
3627db96d56Sopenharmony_ci
3637db96d56Sopenharmony_ci        Write a pickled representation of obj to the open file.
3647db96d56Sopenharmony_ci        [clinic start generated code]*/
3657db96d56Sopenharmony_ci
3667db96d56Sopenharmony_ci11. It's helpful to write a per-parameter docstring for each parameter.
3677db96d56Sopenharmony_ci    But per-parameter docstrings are optional; you can skip this step
3687db96d56Sopenharmony_ci    if you prefer.
3697db96d56Sopenharmony_ci
3707db96d56Sopenharmony_ci    Here's how to add a per-parameter docstring.  The first line
3717db96d56Sopenharmony_ci    of the per-parameter docstring must be indented further than the
3727db96d56Sopenharmony_ci    parameter definition.  The left margin of this first line establishes
3737db96d56Sopenharmony_ci    the left margin for the whole per-parameter docstring; all the text
3747db96d56Sopenharmony_ci    you write will be outdented by this amount.  You can write as much
3757db96d56Sopenharmony_ci    text as you like, across multiple lines if you wish.
3767db96d56Sopenharmony_ci
3777db96d56Sopenharmony_ci    Sample::
3787db96d56Sopenharmony_ci
3797db96d56Sopenharmony_ci        /*[clinic input]
3807db96d56Sopenharmony_ci        module _pickle
3817db96d56Sopenharmony_ci        class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
3827db96d56Sopenharmony_ci        [clinic start generated code]*/
3837db96d56Sopenharmony_ci
3847db96d56Sopenharmony_ci        /*[clinic input]
3857db96d56Sopenharmony_ci        _pickle.Pickler.dump
3867db96d56Sopenharmony_ci
3877db96d56Sopenharmony_ci            obj: 'O'
3887db96d56Sopenharmony_ci                The object to be pickled.
3897db96d56Sopenharmony_ci            /
3907db96d56Sopenharmony_ci
3917db96d56Sopenharmony_ci        Write a pickled representation of obj to the open file.
3927db96d56Sopenharmony_ci        [clinic start generated code]*/
3937db96d56Sopenharmony_ci
3947db96d56Sopenharmony_ci12. Save and close the file, then run ``Tools/clinic/clinic.py`` on
3957db96d56Sopenharmony_ci    it.  With luck everything worked---your block now has output, and
3967db96d56Sopenharmony_ci    a ``.c.h`` file has been generated! Reopen the file in your
3977db96d56Sopenharmony_ci    text editor to see::
3987db96d56Sopenharmony_ci
3997db96d56Sopenharmony_ci       /*[clinic input]
4007db96d56Sopenharmony_ci       _pickle.Pickler.dump
4017db96d56Sopenharmony_ci
4027db96d56Sopenharmony_ci           obj: 'O'
4037db96d56Sopenharmony_ci               The object to be pickled.
4047db96d56Sopenharmony_ci           /
4057db96d56Sopenharmony_ci
4067db96d56Sopenharmony_ci       Write a pickled representation of obj to the open file.
4077db96d56Sopenharmony_ci       [clinic start generated code]*/
4087db96d56Sopenharmony_ci
4097db96d56Sopenharmony_ci       static PyObject *
4107db96d56Sopenharmony_ci       _pickle_Pickler_dump(PicklerObject *self, PyObject *obj)
4117db96d56Sopenharmony_ci       /*[clinic end generated code: output=87ecad1261e02ac7 input=552eb1c0f52260d9]*/
4127db96d56Sopenharmony_ci
4137db96d56Sopenharmony_ci    Obviously, if Argument Clinic didn't produce any output, it's because
4147db96d56Sopenharmony_ci    it found an error in your input.  Keep fixing your errors and retrying
4157db96d56Sopenharmony_ci    until Argument Clinic processes your file without complaint.
4167db96d56Sopenharmony_ci
4177db96d56Sopenharmony_ci    For readability, most of the glue code has been generated to a ``.c.h``
4187db96d56Sopenharmony_ci    file.  You'll need to include that in your original ``.c`` file,
4197db96d56Sopenharmony_ci    typically right after the clinic module block::
4207db96d56Sopenharmony_ci
4217db96d56Sopenharmony_ci       #include "clinic/_pickle.c.h"
4227db96d56Sopenharmony_ci
4237db96d56Sopenharmony_ci13. Double-check that the argument-parsing code Argument Clinic generated
4247db96d56Sopenharmony_ci    looks basically the same as the existing code.
4257db96d56Sopenharmony_ci
4267db96d56Sopenharmony_ci    First, ensure both places use the same argument-parsing function.
4277db96d56Sopenharmony_ci    The existing code must call either
4287db96d56Sopenharmony_ci    :c:func:`PyArg_ParseTuple` or :c:func:`PyArg_ParseTupleAndKeywords`;
4297db96d56Sopenharmony_ci    ensure that the code generated by Argument Clinic calls the
4307db96d56Sopenharmony_ci    *exact* same function.
4317db96d56Sopenharmony_ci
4327db96d56Sopenharmony_ci    Second, the format string passed in to :c:func:`PyArg_ParseTuple` or
4337db96d56Sopenharmony_ci    :c:func:`PyArg_ParseTupleAndKeywords` should be *exactly* the same
4347db96d56Sopenharmony_ci    as the hand-written one in the existing function, up to the colon
4357db96d56Sopenharmony_ci    or semi-colon.
4367db96d56Sopenharmony_ci
4377db96d56Sopenharmony_ci    (Argument Clinic always generates its format strings
4387db96d56Sopenharmony_ci    with a ``:`` followed by the name of the function.  If the
4397db96d56Sopenharmony_ci    existing code's format string ends with ``;``, to provide
4407db96d56Sopenharmony_ci    usage help, this change is harmless—don't worry about it.)
4417db96d56Sopenharmony_ci
4427db96d56Sopenharmony_ci    Third, for parameters whose format units require two arguments
4437db96d56Sopenharmony_ci    (like a length variable, or an encoding string, or a pointer
4447db96d56Sopenharmony_ci    to a conversion function), ensure that the second argument is
4457db96d56Sopenharmony_ci    *exactly* the same between the two invocations.
4467db96d56Sopenharmony_ci
4477db96d56Sopenharmony_ci    Fourth, inside the output portion of the block you'll find a preprocessor
4487db96d56Sopenharmony_ci    macro defining the appropriate static :c:type:`PyMethodDef` structure for
4497db96d56Sopenharmony_ci    this builtin::
4507db96d56Sopenharmony_ci
4517db96d56Sopenharmony_ci        #define __PICKLE_PICKLER_DUMP_METHODDEF    \
4527db96d56Sopenharmony_ci        {"dump", (PyCFunction)__pickle_Pickler_dump, METH_O, __pickle_Pickler_dump__doc__},
4537db96d56Sopenharmony_ci
4547db96d56Sopenharmony_ci    This static structure should be *exactly* the same as the existing static
4557db96d56Sopenharmony_ci    :c:type:`PyMethodDef` structure for this builtin.
4567db96d56Sopenharmony_ci
4577db96d56Sopenharmony_ci    If any of these items differ in *any way*,
4587db96d56Sopenharmony_ci    adjust your Argument Clinic function specification and rerun
4597db96d56Sopenharmony_ci    ``Tools/clinic/clinic.py`` until they *are* the same.
4607db96d56Sopenharmony_ci
4617db96d56Sopenharmony_ci
4627db96d56Sopenharmony_ci14. Notice that the last line of its output is the declaration
4637db96d56Sopenharmony_ci    of your "impl" function.  This is where the builtin's implementation goes.
4647db96d56Sopenharmony_ci    Delete the existing prototype of the function you're modifying, but leave
4657db96d56Sopenharmony_ci    the opening curly brace.  Now delete its argument parsing code and the
4667db96d56Sopenharmony_ci    declarations of all the variables it dumps the arguments into.
4677db96d56Sopenharmony_ci    Notice how the Python arguments are now arguments to this impl function;
4687db96d56Sopenharmony_ci    if the implementation used different names for these variables, fix it.
4697db96d56Sopenharmony_ci
4707db96d56Sopenharmony_ci    Let's reiterate, just because it's kind of weird.  Your code should now
4717db96d56Sopenharmony_ci    look like this::
4727db96d56Sopenharmony_ci
4737db96d56Sopenharmony_ci        static return_type
4747db96d56Sopenharmony_ci        your_function_impl(...)
4757db96d56Sopenharmony_ci        /*[clinic end generated code: checksum=...]*/
4767db96d56Sopenharmony_ci        {
4777db96d56Sopenharmony_ci        ...
4787db96d56Sopenharmony_ci
4797db96d56Sopenharmony_ci    Argument Clinic generated the checksum line and the function prototype just
4807db96d56Sopenharmony_ci    above it.  You should write the opening (and closing) curly braces for the
4817db96d56Sopenharmony_ci    function, and the implementation inside.
4827db96d56Sopenharmony_ci
4837db96d56Sopenharmony_ci    Sample::
4847db96d56Sopenharmony_ci
4857db96d56Sopenharmony_ci        /*[clinic input]
4867db96d56Sopenharmony_ci        module _pickle
4877db96d56Sopenharmony_ci        class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
4887db96d56Sopenharmony_ci        [clinic start generated code]*/
4897db96d56Sopenharmony_ci        /*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/
4907db96d56Sopenharmony_ci
4917db96d56Sopenharmony_ci        /*[clinic input]
4927db96d56Sopenharmony_ci        _pickle.Pickler.dump
4937db96d56Sopenharmony_ci
4947db96d56Sopenharmony_ci            obj: 'O'
4957db96d56Sopenharmony_ci                The object to be pickled.
4967db96d56Sopenharmony_ci            /
4977db96d56Sopenharmony_ci
4987db96d56Sopenharmony_ci        Write a pickled representation of obj to the open file.
4997db96d56Sopenharmony_ci        [clinic start generated code]*/
5007db96d56Sopenharmony_ci
5017db96d56Sopenharmony_ci        PyDoc_STRVAR(__pickle_Pickler_dump__doc__,
5027db96d56Sopenharmony_ci        "Write a pickled representation of obj to the open file.\n"
5037db96d56Sopenharmony_ci        "\n"
5047db96d56Sopenharmony_ci        ...
5057db96d56Sopenharmony_ci        static PyObject *
5067db96d56Sopenharmony_ci        _pickle_Pickler_dump_impl(PicklerObject *self, PyObject *obj)
5077db96d56Sopenharmony_ci        /*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/
5087db96d56Sopenharmony_ci        {
5097db96d56Sopenharmony_ci            /* Check whether the Pickler was initialized correctly (issue3664).
5107db96d56Sopenharmony_ci               Developers often forget to call __init__() in their subclasses, which
5117db96d56Sopenharmony_ci               would trigger a segfault without this check. */
5127db96d56Sopenharmony_ci            if (self->write == NULL) {
5137db96d56Sopenharmony_ci                PyErr_Format(PicklingError,
5147db96d56Sopenharmony_ci                             "Pickler.__init__() was not called by %s.__init__()",
5157db96d56Sopenharmony_ci                             Py_TYPE(self)->tp_name);
5167db96d56Sopenharmony_ci                return NULL;
5177db96d56Sopenharmony_ci            }
5187db96d56Sopenharmony_ci
5197db96d56Sopenharmony_ci            if (_Pickler_ClearBuffer(self) < 0)
5207db96d56Sopenharmony_ci                return NULL;
5217db96d56Sopenharmony_ci
5227db96d56Sopenharmony_ci            ...
5237db96d56Sopenharmony_ci
5247db96d56Sopenharmony_ci15. Remember the macro with the :c:type:`PyMethodDef` structure for this
5257db96d56Sopenharmony_ci    function?  Find the existing :c:type:`PyMethodDef` structure for this
5267db96d56Sopenharmony_ci    function and replace it with a reference to the macro.  (If the builtin
5277db96d56Sopenharmony_ci    is at module scope, this will probably be very near the end of the file;
5287db96d56Sopenharmony_ci    if the builtin is a class method, this will probably be below but relatively
5297db96d56Sopenharmony_ci    near to the implementation.)
5307db96d56Sopenharmony_ci
5317db96d56Sopenharmony_ci    Note that the body of the macro contains a trailing comma.  So when you
5327db96d56Sopenharmony_ci    replace the existing static :c:type:`PyMethodDef` structure with the macro,
5337db96d56Sopenharmony_ci    *don't* add a comma to the end.
5347db96d56Sopenharmony_ci
5357db96d56Sopenharmony_ci    Sample::
5367db96d56Sopenharmony_ci
5377db96d56Sopenharmony_ci        static struct PyMethodDef Pickler_methods[] = {
5387db96d56Sopenharmony_ci            __PICKLE_PICKLER_DUMP_METHODDEF
5397db96d56Sopenharmony_ci            __PICKLE_PICKLER_CLEAR_MEMO_METHODDEF
5407db96d56Sopenharmony_ci            {NULL, NULL}                /* sentinel */
5417db96d56Sopenharmony_ci        };
5427db96d56Sopenharmony_ci
5437db96d56Sopenharmony_ci
5447db96d56Sopenharmony_ci16. Compile, then run the relevant portions of the regression-test suite.
5457db96d56Sopenharmony_ci    This change should not introduce any new compile-time warnings or errors,
5467db96d56Sopenharmony_ci    and there should be no externally visible change to Python's behavior.
5477db96d56Sopenharmony_ci
5487db96d56Sopenharmony_ci    Well, except for one difference: ``inspect.signature()`` run on your function
5497db96d56Sopenharmony_ci    should now provide a valid signature!
5507db96d56Sopenharmony_ci
5517db96d56Sopenharmony_ci    Congratulations, you've ported your first function to work with Argument Clinic!
5527db96d56Sopenharmony_ci
5537db96d56Sopenharmony_ciAdvanced Topics
5547db96d56Sopenharmony_ci===============
5557db96d56Sopenharmony_ci
5567db96d56Sopenharmony_ciNow that you've had some experience working with Argument Clinic, it's time
5577db96d56Sopenharmony_cifor some advanced topics.
5587db96d56Sopenharmony_ci
5597db96d56Sopenharmony_ci
5607db96d56Sopenharmony_ciSymbolic default values
5617db96d56Sopenharmony_ci-----------------------
5627db96d56Sopenharmony_ci
5637db96d56Sopenharmony_ciThe default value you provide for a parameter can't be any arbitrary
5647db96d56Sopenharmony_ciexpression.  Currently the following are explicitly supported:
5657db96d56Sopenharmony_ci
5667db96d56Sopenharmony_ci* Numeric constants (integer and float)
5677db96d56Sopenharmony_ci* String constants
5687db96d56Sopenharmony_ci* ``True``, ``False``, and ``None``
5697db96d56Sopenharmony_ci* Simple symbolic constants like ``sys.maxsize``, which must
5707db96d56Sopenharmony_ci  start with the name of the module
5717db96d56Sopenharmony_ci
5727db96d56Sopenharmony_ci(In the future, this may need to get even more elaborate,
5737db96d56Sopenharmony_cito allow full expressions like ``CONSTANT - 1``.)
5747db96d56Sopenharmony_ci
5757db96d56Sopenharmony_ci
5767db96d56Sopenharmony_ciRenaming the C functions and variables generated by Argument Clinic
5777db96d56Sopenharmony_ci-------------------------------------------------------------------
5787db96d56Sopenharmony_ci
5797db96d56Sopenharmony_ciArgument Clinic automatically names the functions it generates for you.
5807db96d56Sopenharmony_ciOccasionally this may cause a problem, if the generated name collides with
5817db96d56Sopenharmony_cithe name of an existing C function.  There's an easy solution: override the names
5827db96d56Sopenharmony_ciused for the C functions.  Just add the keyword ``"as"``
5837db96d56Sopenharmony_cito your function declaration line, followed by the function name you wish to use.
5847db96d56Sopenharmony_ciArgument Clinic will use that function name for the base (generated) function,
5857db96d56Sopenharmony_cithen add ``"_impl"`` to the end and use that for the name of the impl function.
5867db96d56Sopenharmony_ci
5877db96d56Sopenharmony_ciFor example, if we wanted to rename the C function names generated for
5887db96d56Sopenharmony_ci``pickle.Pickler.dump``, it'd look like this::
5897db96d56Sopenharmony_ci
5907db96d56Sopenharmony_ci    /*[clinic input]
5917db96d56Sopenharmony_ci    pickle.Pickler.dump as pickler_dumper
5927db96d56Sopenharmony_ci
5937db96d56Sopenharmony_ci    ...
5947db96d56Sopenharmony_ci
5957db96d56Sopenharmony_ciThe base function would now be named ``pickler_dumper()``,
5967db96d56Sopenharmony_ciand the impl function would now be named ``pickler_dumper_impl()``.
5977db96d56Sopenharmony_ci
5987db96d56Sopenharmony_ci
5997db96d56Sopenharmony_ciSimilarly, you may have a problem where you want to give a parameter
6007db96d56Sopenharmony_cia specific Python name, but that name may be inconvenient in C.  Argument
6017db96d56Sopenharmony_ciClinic allows you to give a parameter different names in Python and in C,
6027db96d56Sopenharmony_ciusing the same ``"as"`` syntax::
6037db96d56Sopenharmony_ci
6047db96d56Sopenharmony_ci    /*[clinic input]
6057db96d56Sopenharmony_ci    pickle.Pickler.dump
6067db96d56Sopenharmony_ci
6077db96d56Sopenharmony_ci        obj: object
6087db96d56Sopenharmony_ci        file as file_obj: object
6097db96d56Sopenharmony_ci        protocol: object = NULL
6107db96d56Sopenharmony_ci        *
6117db96d56Sopenharmony_ci        fix_imports: bool = True
6127db96d56Sopenharmony_ci
6137db96d56Sopenharmony_ciHere, the name used in Python (in the signature and the ``keywords``
6147db96d56Sopenharmony_ciarray) would be ``file``, but the C variable would be named ``file_obj``.
6157db96d56Sopenharmony_ci
6167db96d56Sopenharmony_ciYou can use this to rename the ``self`` parameter too!
6177db96d56Sopenharmony_ci
6187db96d56Sopenharmony_ci
6197db96d56Sopenharmony_ciConverting functions using PyArg_UnpackTuple
6207db96d56Sopenharmony_ci--------------------------------------------
6217db96d56Sopenharmony_ci
6227db96d56Sopenharmony_ciTo convert a function parsing its arguments with :c:func:`PyArg_UnpackTuple`,
6237db96d56Sopenharmony_cisimply write out all the arguments, specifying each as an ``object``.  You
6247db96d56Sopenharmony_cimay specify the ``type`` argument to cast the type as appropriate.  All
6257db96d56Sopenharmony_ciarguments should be marked positional-only (add a ``/`` on a line by itself
6267db96d56Sopenharmony_ciafter the last argument).
6277db96d56Sopenharmony_ci
6287db96d56Sopenharmony_ciCurrently the generated code will use :c:func:`PyArg_ParseTuple`, but this
6297db96d56Sopenharmony_ciwill change soon.
6307db96d56Sopenharmony_ci
6317db96d56Sopenharmony_ciOptional Groups
6327db96d56Sopenharmony_ci---------------
6337db96d56Sopenharmony_ci
6347db96d56Sopenharmony_ciSome legacy functions have a tricky approach to parsing their arguments:
6357db96d56Sopenharmony_cithey count the number of positional arguments, then use a ``switch`` statement
6367db96d56Sopenharmony_cito call one of several different :c:func:`PyArg_ParseTuple` calls depending on
6377db96d56Sopenharmony_cihow many positional arguments there are.  (These functions cannot accept
6387db96d56Sopenharmony_cikeyword-only arguments.)  This approach was used to simulate optional
6397db96d56Sopenharmony_ciarguments back before :c:func:`PyArg_ParseTupleAndKeywords` was created.
6407db96d56Sopenharmony_ci
6417db96d56Sopenharmony_ciWhile functions using this approach can often be converted to
6427db96d56Sopenharmony_ciuse :c:func:`PyArg_ParseTupleAndKeywords`, optional arguments, and default values,
6437db96d56Sopenharmony_ciit's not always possible.  Some of these legacy functions have
6447db96d56Sopenharmony_cibehaviors :c:func:`PyArg_ParseTupleAndKeywords` doesn't directly support.
6457db96d56Sopenharmony_ciThe most obvious example is the builtin function ``range()``, which has
6467db96d56Sopenharmony_cian optional argument on the *left* side of its required argument!
6477db96d56Sopenharmony_ciAnother example is ``curses.window.addch()``, which has a group of two
6487db96d56Sopenharmony_ciarguments that must always be specified together.  (The arguments are
6497db96d56Sopenharmony_cicalled ``x`` and ``y``; if you call the function passing in ``x``,
6507db96d56Sopenharmony_ciyou must also pass in ``y``—and if you don't pass in ``x`` you may not
6517db96d56Sopenharmony_cipass in ``y`` either.)
6527db96d56Sopenharmony_ci
6537db96d56Sopenharmony_ciIn any case, the goal of Argument Clinic is to support argument parsing
6547db96d56Sopenharmony_cifor all existing CPython builtins without changing their semantics.
6557db96d56Sopenharmony_ciTherefore Argument Clinic supports
6567db96d56Sopenharmony_cithis alternate approach to parsing, using what are called *optional groups*.
6577db96d56Sopenharmony_ciOptional groups are groups of arguments that must all be passed in together.
6587db96d56Sopenharmony_ciThey can be to the left or the right of the required arguments.  They
6597db96d56Sopenharmony_cican *only* be used with positional-only parameters.
6607db96d56Sopenharmony_ci
6617db96d56Sopenharmony_ci.. note:: Optional groups are *only* intended for use when converting
6627db96d56Sopenharmony_ci          functions that make multiple calls to :c:func:`PyArg_ParseTuple`!
6637db96d56Sopenharmony_ci          Functions that use *any* other approach for parsing arguments
6647db96d56Sopenharmony_ci          should *almost never* be converted to Argument Clinic using
6657db96d56Sopenharmony_ci          optional groups.  Functions using optional groups currently
6667db96d56Sopenharmony_ci          cannot have accurate signatures in Python, because Python just
6677db96d56Sopenharmony_ci          doesn't understand the concept.  Please avoid using optional
6687db96d56Sopenharmony_ci          groups wherever possible.
6697db96d56Sopenharmony_ci
6707db96d56Sopenharmony_ciTo specify an optional group, add a ``[`` on a line by itself before
6717db96d56Sopenharmony_cithe parameters you wish to group together, and a ``]`` on a line by itself
6727db96d56Sopenharmony_ciafter these parameters.  As an example, here's how ``curses.window.addch``
6737db96d56Sopenharmony_ciuses optional groups to make the first two parameters and the last
6747db96d56Sopenharmony_ciparameter optional::
6757db96d56Sopenharmony_ci
6767db96d56Sopenharmony_ci    /*[clinic input]
6777db96d56Sopenharmony_ci
6787db96d56Sopenharmony_ci    curses.window.addch
6797db96d56Sopenharmony_ci
6807db96d56Sopenharmony_ci        [
6817db96d56Sopenharmony_ci        x: int
6827db96d56Sopenharmony_ci          X-coordinate.
6837db96d56Sopenharmony_ci        y: int
6847db96d56Sopenharmony_ci          Y-coordinate.
6857db96d56Sopenharmony_ci        ]
6867db96d56Sopenharmony_ci
6877db96d56Sopenharmony_ci        ch: object
6887db96d56Sopenharmony_ci          Character to add.
6897db96d56Sopenharmony_ci
6907db96d56Sopenharmony_ci        [
6917db96d56Sopenharmony_ci        attr: long
6927db96d56Sopenharmony_ci          Attributes for the character.
6937db96d56Sopenharmony_ci        ]
6947db96d56Sopenharmony_ci        /
6957db96d56Sopenharmony_ci
6967db96d56Sopenharmony_ci    ...
6977db96d56Sopenharmony_ci
6987db96d56Sopenharmony_ci
6997db96d56Sopenharmony_ciNotes:
7007db96d56Sopenharmony_ci
7017db96d56Sopenharmony_ci* For every optional group, one additional parameter will be passed into the
7027db96d56Sopenharmony_ci  impl function representing the group.  The parameter will be an int named
7037db96d56Sopenharmony_ci  ``group_{direction}_{number}``,
7047db96d56Sopenharmony_ci  where ``{direction}`` is either ``right`` or ``left`` depending on whether the group
7057db96d56Sopenharmony_ci  is before or after the required parameters, and ``{number}`` is a monotonically
7067db96d56Sopenharmony_ci  increasing number (starting at 1) indicating how far away the group is from
7077db96d56Sopenharmony_ci  the required parameters.  When the impl is called, this parameter will be set
7087db96d56Sopenharmony_ci  to zero if this group was unused, and set to non-zero if this group was used.
7097db96d56Sopenharmony_ci  (By used or unused, I mean whether or not the parameters received arguments
7107db96d56Sopenharmony_ci  in this invocation.)
7117db96d56Sopenharmony_ci
7127db96d56Sopenharmony_ci* If there are no required arguments, the optional groups will behave
7137db96d56Sopenharmony_ci  as if they're to the right of the required arguments.
7147db96d56Sopenharmony_ci
7157db96d56Sopenharmony_ci* In the case of ambiguity, the argument parsing code
7167db96d56Sopenharmony_ci  favors parameters on the left (before the required parameters).
7177db96d56Sopenharmony_ci
7187db96d56Sopenharmony_ci* Optional groups can only contain positional-only parameters.
7197db96d56Sopenharmony_ci
7207db96d56Sopenharmony_ci* Optional groups are *only* intended for legacy code.  Please do not
7217db96d56Sopenharmony_ci  use optional groups for new code.
7227db96d56Sopenharmony_ci
7237db96d56Sopenharmony_ci
7247db96d56Sopenharmony_ciUsing real Argument Clinic converters, instead of "legacy converters"
7257db96d56Sopenharmony_ci---------------------------------------------------------------------
7267db96d56Sopenharmony_ci
7277db96d56Sopenharmony_ciTo save time, and to minimize how much you need to learn
7287db96d56Sopenharmony_cito achieve your first port to Argument Clinic, the walkthrough above tells
7297db96d56Sopenharmony_ciyou to use "legacy converters".  "Legacy converters" are a convenience,
7307db96d56Sopenharmony_cidesigned explicitly to make porting existing code to Argument Clinic
7317db96d56Sopenharmony_cieasier.  And to be clear, their use is acceptable when porting code for
7327db96d56Sopenharmony_ciPython 3.4.
7337db96d56Sopenharmony_ci
7347db96d56Sopenharmony_ciHowever, in the long term we probably want all our blocks to
7357db96d56Sopenharmony_ciuse Argument Clinic's real syntax for converters.  Why?  A couple
7367db96d56Sopenharmony_cireasons:
7377db96d56Sopenharmony_ci
7387db96d56Sopenharmony_ci* The proper converters are far easier to read and clearer in their intent.
7397db96d56Sopenharmony_ci* There are some format units that are unsupported as "legacy converters",
7407db96d56Sopenharmony_ci  because they require arguments, and the legacy converter syntax doesn't
7417db96d56Sopenharmony_ci  support specifying arguments.
7427db96d56Sopenharmony_ci* In the future we may have a new argument parsing library that isn't
7437db96d56Sopenharmony_ci  restricted to what :c:func:`PyArg_ParseTuple` supports; this flexibility
7447db96d56Sopenharmony_ci  won't be available to parameters using legacy converters.
7457db96d56Sopenharmony_ci
7467db96d56Sopenharmony_ciTherefore, if you don't mind a little extra effort, please use the normal
7477db96d56Sopenharmony_ciconverters instead of legacy converters.
7487db96d56Sopenharmony_ci
7497db96d56Sopenharmony_ciIn a nutshell, the syntax for Argument Clinic (non-legacy) converters
7507db96d56Sopenharmony_cilooks like a Python function call.  However, if there are no explicit
7517db96d56Sopenharmony_ciarguments to the function (all functions take their default values),
7527db96d56Sopenharmony_ciyou may omit the parentheses.  Thus ``bool`` and ``bool()`` are exactly
7537db96d56Sopenharmony_cithe same converters.
7547db96d56Sopenharmony_ci
7557db96d56Sopenharmony_ciAll arguments to Argument Clinic converters are keyword-only.
7567db96d56Sopenharmony_ciAll Argument Clinic converters accept the following arguments:
7577db96d56Sopenharmony_ci
7587db96d56Sopenharmony_ci  ``c_default``
7597db96d56Sopenharmony_ci    The default value for this parameter when defined in C.
7607db96d56Sopenharmony_ci    Specifically, this will be the initializer for the variable declared
7617db96d56Sopenharmony_ci    in the "parse function".  See :ref:`the section on default values <default_values>`
7627db96d56Sopenharmony_ci    for how to use this.
7637db96d56Sopenharmony_ci    Specified as a string.
7647db96d56Sopenharmony_ci
7657db96d56Sopenharmony_ci  ``annotation``
7667db96d56Sopenharmony_ci    The annotation value for this parameter.  Not currently supported,
7677db96d56Sopenharmony_ci    because :pep:`8` mandates that the Python library may not use
7687db96d56Sopenharmony_ci    annotations.
7697db96d56Sopenharmony_ci
7707db96d56Sopenharmony_ciIn addition, some converters accept additional arguments.  Here is a list
7717db96d56Sopenharmony_ciof these arguments, along with their meanings:
7727db96d56Sopenharmony_ci
7737db96d56Sopenharmony_ci  ``accept``
7747db96d56Sopenharmony_ci    A set of Python types (and possibly pseudo-types);
7757db96d56Sopenharmony_ci    this restricts the allowable Python argument to values of these types.
7767db96d56Sopenharmony_ci    (This is not a general-purpose facility; as a rule it only supports
7777db96d56Sopenharmony_ci    specific lists of types as shown in the legacy converter table.)
7787db96d56Sopenharmony_ci
7797db96d56Sopenharmony_ci    To accept ``None``, add ``NoneType`` to this set.
7807db96d56Sopenharmony_ci
7817db96d56Sopenharmony_ci  ``bitwise``
7827db96d56Sopenharmony_ci    Only supported for unsigned integers.  The native integer value of this
7837db96d56Sopenharmony_ci    Python argument will be written to the parameter without any range checking,
7847db96d56Sopenharmony_ci    even for negative values.
7857db96d56Sopenharmony_ci
7867db96d56Sopenharmony_ci  ``converter``
7877db96d56Sopenharmony_ci    Only supported by the ``object`` converter.  Specifies the name of a
7887db96d56Sopenharmony_ci    :ref:`C "converter function" <o_ampersand>`
7897db96d56Sopenharmony_ci    to use to convert this object to a native type.
7907db96d56Sopenharmony_ci
7917db96d56Sopenharmony_ci  ``encoding``
7927db96d56Sopenharmony_ci    Only supported for strings.  Specifies the encoding to use when converting
7937db96d56Sopenharmony_ci    this string from a Python str (Unicode) value into a C ``char *`` value.
7947db96d56Sopenharmony_ci
7957db96d56Sopenharmony_ci
7967db96d56Sopenharmony_ci  ``subclass_of``
7977db96d56Sopenharmony_ci    Only supported for the ``object`` converter.  Requires that the Python
7987db96d56Sopenharmony_ci    value be a subclass of a Python type, as expressed in C.
7997db96d56Sopenharmony_ci
8007db96d56Sopenharmony_ci  ``type``
8017db96d56Sopenharmony_ci    Only supported for the ``object`` and ``self`` converters.  Specifies
8027db96d56Sopenharmony_ci    the C type that will be used to declare the variable.  Default value is
8037db96d56Sopenharmony_ci    ``"PyObject *"``.
8047db96d56Sopenharmony_ci
8057db96d56Sopenharmony_ci  ``zeroes``
8067db96d56Sopenharmony_ci    Only supported for strings.  If true, embedded NUL bytes (``'\\0'``) are
8077db96d56Sopenharmony_ci    permitted inside the value.  The length of the string will be passed in
8087db96d56Sopenharmony_ci    to the impl function, just after the string parameter, as a parameter named
8097db96d56Sopenharmony_ci    ``<parameter_name>_length``.
8107db96d56Sopenharmony_ci
8117db96d56Sopenharmony_ciPlease note, not every possible combination of arguments will work.
8127db96d56Sopenharmony_ciUsually these arguments are implemented by specific ``PyArg_ParseTuple``
8137db96d56Sopenharmony_ci*format units*, with specific behavior.  For example, currently you cannot
8147db96d56Sopenharmony_cicall ``unsigned_short`` without also specifying ``bitwise=True``.
8157db96d56Sopenharmony_ciAlthough it's perfectly reasonable to think this would work, these semantics don't
8167db96d56Sopenharmony_cimap to any existing format unit.  So Argument Clinic doesn't support it.  (Or, at
8177db96d56Sopenharmony_cileast, not yet.)
8187db96d56Sopenharmony_ci
8197db96d56Sopenharmony_ciBelow is a table showing the mapping of legacy converters into real
8207db96d56Sopenharmony_ciArgument Clinic converters.  On the left is the legacy converter,
8217db96d56Sopenharmony_cion the right is the text you'd replace it with.
8227db96d56Sopenharmony_ci
8237db96d56Sopenharmony_ci=========   =================================================================================
8247db96d56Sopenharmony_ci``'B'``     ``unsigned_char(bitwise=True)``
8257db96d56Sopenharmony_ci``'b'``     ``unsigned_char``
8267db96d56Sopenharmony_ci``'c'``     ``char``
8277db96d56Sopenharmony_ci``'C'``     ``int(accept={str})``
8287db96d56Sopenharmony_ci``'d'``     ``double``
8297db96d56Sopenharmony_ci``'D'``     ``Py_complex``
8307db96d56Sopenharmony_ci``'es'``    ``str(encoding='name_of_encoding')``
8317db96d56Sopenharmony_ci``'es#'``   ``str(encoding='name_of_encoding', zeroes=True)``
8327db96d56Sopenharmony_ci``'et'``    ``str(encoding='name_of_encoding', accept={bytes, bytearray, str})``
8337db96d56Sopenharmony_ci``'et#'``   ``str(encoding='name_of_encoding', accept={bytes, bytearray, str}, zeroes=True)``
8347db96d56Sopenharmony_ci``'f'``     ``float``
8357db96d56Sopenharmony_ci``'h'``     ``short``
8367db96d56Sopenharmony_ci``'H'``     ``unsigned_short(bitwise=True)``
8377db96d56Sopenharmony_ci``'i'``     ``int``
8387db96d56Sopenharmony_ci``'I'``     ``unsigned_int(bitwise=True)``
8397db96d56Sopenharmony_ci``'k'``     ``unsigned_long(bitwise=True)``
8407db96d56Sopenharmony_ci``'K'``     ``unsigned_long_long(bitwise=True)``
8417db96d56Sopenharmony_ci``'l'``     ``long``
8427db96d56Sopenharmony_ci``'L'``     ``long long``
8437db96d56Sopenharmony_ci``'n'``     ``Py_ssize_t``
8447db96d56Sopenharmony_ci``'O'``     ``object``
8457db96d56Sopenharmony_ci``'O!'``    ``object(subclass_of='&PySomething_Type')``
8467db96d56Sopenharmony_ci``'O&'``    ``object(converter='name_of_c_function')``
8477db96d56Sopenharmony_ci``'p'``     ``bool``
8487db96d56Sopenharmony_ci``'S'``     ``PyBytesObject``
8497db96d56Sopenharmony_ci``'s'``     ``str``
8507db96d56Sopenharmony_ci``'s#'``    ``str(zeroes=True)``
8517db96d56Sopenharmony_ci``'s*'``    ``Py_buffer(accept={buffer, str})``
8527db96d56Sopenharmony_ci``'U'``     ``unicode``
8537db96d56Sopenharmony_ci``'u'``     ``Py_UNICODE``
8547db96d56Sopenharmony_ci``'u#'``    ``Py_UNICODE(zeroes=True)``
8557db96d56Sopenharmony_ci``'w*'``    ``Py_buffer(accept={rwbuffer})``
8567db96d56Sopenharmony_ci``'Y'``     ``PyByteArrayObject``
8577db96d56Sopenharmony_ci``'y'``     ``str(accept={bytes})``
8587db96d56Sopenharmony_ci``'y#'``    ``str(accept={robuffer}, zeroes=True)``
8597db96d56Sopenharmony_ci``'y*'``    ``Py_buffer``
8607db96d56Sopenharmony_ci``'Z'``     ``Py_UNICODE(accept={str, NoneType})``
8617db96d56Sopenharmony_ci``'Z#'``    ``Py_UNICODE(accept={str, NoneType}, zeroes=True)``
8627db96d56Sopenharmony_ci``'z'``     ``str(accept={str, NoneType})``
8637db96d56Sopenharmony_ci``'z#'``    ``str(accept={str, NoneType}, zeroes=True)``
8647db96d56Sopenharmony_ci``'z*'``    ``Py_buffer(accept={buffer, str, NoneType})``
8657db96d56Sopenharmony_ci=========   =================================================================================
8667db96d56Sopenharmony_ci
8677db96d56Sopenharmony_ciAs an example, here's our sample ``pickle.Pickler.dump`` using the proper
8687db96d56Sopenharmony_ciconverter::
8697db96d56Sopenharmony_ci
8707db96d56Sopenharmony_ci    /*[clinic input]
8717db96d56Sopenharmony_ci    pickle.Pickler.dump
8727db96d56Sopenharmony_ci
8737db96d56Sopenharmony_ci        obj: object
8747db96d56Sopenharmony_ci            The object to be pickled.
8757db96d56Sopenharmony_ci        /
8767db96d56Sopenharmony_ci
8777db96d56Sopenharmony_ci    Write a pickled representation of obj to the open file.
8787db96d56Sopenharmony_ci    [clinic start generated code]*/
8797db96d56Sopenharmony_ci
8807db96d56Sopenharmony_ciOne advantage of real converters is that they're more flexible than legacy
8817db96d56Sopenharmony_ciconverters.  For example, the ``unsigned_int`` converter (and all the
8827db96d56Sopenharmony_ci``unsigned_`` converters) can be specified without ``bitwise=True``.  Their
8837db96d56Sopenharmony_cidefault behavior performs range checking on the value, and they won't accept
8847db96d56Sopenharmony_cinegative numbers.  You just can't do that with a legacy converter!
8857db96d56Sopenharmony_ci
8867db96d56Sopenharmony_ciArgument Clinic will show you all the converters it has
8877db96d56Sopenharmony_ciavailable.  For each converter it'll show you all the parameters
8887db96d56Sopenharmony_ciit accepts, along with the default value for each parameter.
8897db96d56Sopenharmony_ciJust run ``Tools/clinic/clinic.py --converters`` to see the full list.
8907db96d56Sopenharmony_ci
8917db96d56Sopenharmony_ciPy_buffer
8927db96d56Sopenharmony_ci---------
8937db96d56Sopenharmony_ci
8947db96d56Sopenharmony_ciWhen using the ``Py_buffer`` converter
8957db96d56Sopenharmony_ci(or the ``'s*'``, ``'w*'``, ``'*y'``, or ``'z*'`` legacy converters),
8967db96d56Sopenharmony_ciyou *must* not call :c:func:`PyBuffer_Release` on the provided buffer.
8977db96d56Sopenharmony_ciArgument Clinic generates code that does it for you (in the parsing function).
8987db96d56Sopenharmony_ci
8997db96d56Sopenharmony_ci
9007db96d56Sopenharmony_ci
9017db96d56Sopenharmony_ciAdvanced converters
9027db96d56Sopenharmony_ci-------------------
9037db96d56Sopenharmony_ci
9047db96d56Sopenharmony_ciRemember those format units you skipped for your first
9057db96d56Sopenharmony_citime because they were advanced?  Here's how to handle those too.
9067db96d56Sopenharmony_ci
9077db96d56Sopenharmony_ciThe trick is, all those format units take arguments—either
9087db96d56Sopenharmony_ciconversion functions, or types, or strings specifying an encoding.
9097db96d56Sopenharmony_ci(But "legacy converters" don't support arguments.  That's why we
9107db96d56Sopenharmony_ciskipped them for your first function.)  The argument you specified
9117db96d56Sopenharmony_cito the format unit is now an argument to the converter; this
9127db96d56Sopenharmony_ciargument is either ``converter`` (for ``O&``), ``subclass_of`` (for ``O!``),
9137db96d56Sopenharmony_cior ``encoding`` (for all the format units that start with ``e``).
9147db96d56Sopenharmony_ci
9157db96d56Sopenharmony_ciWhen using ``subclass_of``, you may also want to use the other
9167db96d56Sopenharmony_cicustom argument for ``object()``: ``type``, which lets you set the type
9177db96d56Sopenharmony_ciactually used for the parameter.  For example, if you want to ensure
9187db96d56Sopenharmony_cithat the object is a subclass of ``PyUnicode_Type``, you probably want
9197db96d56Sopenharmony_cito use the converter ``object(type='PyUnicodeObject *', subclass_of='&PyUnicode_Type')``.
9207db96d56Sopenharmony_ci
9217db96d56Sopenharmony_ciOne possible problem with using Argument Clinic: it takes away some possible
9227db96d56Sopenharmony_ciflexibility for the format units starting with ``e``.  When writing a
9237db96d56Sopenharmony_ci``PyArg_Parse`` call by hand, you could theoretically decide at runtime what
9247db96d56Sopenharmony_ciencoding string to pass in to :c:func:`PyArg_ParseTuple`.   But now this string must
9257db96d56Sopenharmony_cibe hard-coded at Argument-Clinic-preprocessing-time.  This limitation is deliberate;
9267db96d56Sopenharmony_ciit made supporting this format unit much easier, and may allow for future optimizations.
9277db96d56Sopenharmony_ciThis restriction doesn't seem unreasonable; CPython itself always passes in static
9287db96d56Sopenharmony_cihard-coded encoding strings for parameters whose format units start with ``e``.
9297db96d56Sopenharmony_ci
9307db96d56Sopenharmony_ci
9317db96d56Sopenharmony_ci.. _default_values:
9327db96d56Sopenharmony_ci
9337db96d56Sopenharmony_ciParameter default values
9347db96d56Sopenharmony_ci------------------------
9357db96d56Sopenharmony_ci
9367db96d56Sopenharmony_ciDefault values for parameters can be any of a number of values.
9377db96d56Sopenharmony_ciAt their simplest, they can be string, int, or float literals:
9387db96d56Sopenharmony_ci
9397db96d56Sopenharmony_ci.. code-block:: none
9407db96d56Sopenharmony_ci
9417db96d56Sopenharmony_ci    foo: str = "abc"
9427db96d56Sopenharmony_ci    bar: int = 123
9437db96d56Sopenharmony_ci    bat: float = 45.6
9447db96d56Sopenharmony_ci
9457db96d56Sopenharmony_ciThey can also use any of Python's built-in constants:
9467db96d56Sopenharmony_ci
9477db96d56Sopenharmony_ci.. code-block:: none
9487db96d56Sopenharmony_ci
9497db96d56Sopenharmony_ci    yep:  bool = True
9507db96d56Sopenharmony_ci    nope: bool = False
9517db96d56Sopenharmony_ci    nada: object = None
9527db96d56Sopenharmony_ci
9537db96d56Sopenharmony_ciThere's also special support for a default value of ``NULL``, and
9547db96d56Sopenharmony_cifor simple expressions, documented in the following sections.
9557db96d56Sopenharmony_ci
9567db96d56Sopenharmony_ci
9577db96d56Sopenharmony_ciThe ``NULL`` default value
9587db96d56Sopenharmony_ci--------------------------
9597db96d56Sopenharmony_ci
9607db96d56Sopenharmony_ciFor string and object parameters, you can set them to ``None`` to indicate
9617db96d56Sopenharmony_cithat there's no default.  However, that means the C variable will be
9627db96d56Sopenharmony_ciinitialized to ``Py_None``.  For convenience's sakes, there's a special
9637db96d56Sopenharmony_civalue called ``NULL`` for just this reason: from Python's perspective it
9647db96d56Sopenharmony_cibehaves like a default value of ``None``, but the C variable is initialized
9657db96d56Sopenharmony_ciwith ``NULL``.
9667db96d56Sopenharmony_ci
9677db96d56Sopenharmony_ciExpressions specified as default values
9687db96d56Sopenharmony_ci---------------------------------------
9697db96d56Sopenharmony_ci
9707db96d56Sopenharmony_ciThe default value for a parameter can be more than just a literal value.
9717db96d56Sopenharmony_ciIt can be an entire expression, using math operators and looking up attributes
9727db96d56Sopenharmony_cion objects.  However, this support isn't exactly simple, because of some
9737db96d56Sopenharmony_cinon-obvious semantics.
9747db96d56Sopenharmony_ci
9757db96d56Sopenharmony_ciConsider the following example:
9767db96d56Sopenharmony_ci
9777db96d56Sopenharmony_ci.. code-block:: none
9787db96d56Sopenharmony_ci
9797db96d56Sopenharmony_ci    foo: Py_ssize_t = sys.maxsize - 1
9807db96d56Sopenharmony_ci
9817db96d56Sopenharmony_ci``sys.maxsize`` can have different values on different platforms.  Therefore
9827db96d56Sopenharmony_ciArgument Clinic can't simply evaluate that expression locally and hard-code it
9837db96d56Sopenharmony_ciin C.  So it stores the default in such a way that it will get evaluated at
9847db96d56Sopenharmony_ciruntime, when the user asks for the function's signature.
9857db96d56Sopenharmony_ci
9867db96d56Sopenharmony_ciWhat namespace is available when the expression is evaluated?  It's evaluated
9877db96d56Sopenharmony_ciin the context of the module the builtin came from.  So, if your module has an
9887db96d56Sopenharmony_ciattribute called "``max_widgets``", you may simply use it:
9897db96d56Sopenharmony_ci
9907db96d56Sopenharmony_ci.. code-block:: none
9917db96d56Sopenharmony_ci
9927db96d56Sopenharmony_ci    foo: Py_ssize_t = max_widgets
9937db96d56Sopenharmony_ci
9947db96d56Sopenharmony_ciIf the symbol isn't found in the current module, it fails over to looking in
9957db96d56Sopenharmony_ci``sys.modules``.  That's how it can find ``sys.maxsize`` for example.  (Since you
9967db96d56Sopenharmony_cidon't know in advance what modules the user will load into their interpreter,
9977db96d56Sopenharmony_ciit's best to restrict yourself to modules that are preloaded by Python itself.)
9987db96d56Sopenharmony_ci
9997db96d56Sopenharmony_ciEvaluating default values only at runtime means Argument Clinic can't compute
10007db96d56Sopenharmony_cithe correct equivalent C default value.  So you need to tell it explicitly.
10017db96d56Sopenharmony_ciWhen you use an expression, you must also specify the equivalent expression
10027db96d56Sopenharmony_ciin C, using the ``c_default`` parameter to the converter:
10037db96d56Sopenharmony_ci
10047db96d56Sopenharmony_ci.. code-block:: none
10057db96d56Sopenharmony_ci
10067db96d56Sopenharmony_ci    foo: Py_ssize_t(c_default="PY_SSIZE_T_MAX - 1") = sys.maxsize - 1
10077db96d56Sopenharmony_ci
10087db96d56Sopenharmony_ciAnother complication: Argument Clinic can't know in advance whether or not the
10097db96d56Sopenharmony_ciexpression you supply is valid.  It parses it to make sure it looks legal, but
10107db96d56Sopenharmony_ciit can't *actually* know.  You must be very careful when using expressions to
10117db96d56Sopenharmony_cispecify values that are guaranteed to be valid at runtime!
10127db96d56Sopenharmony_ci
10137db96d56Sopenharmony_ciFinally, because expressions must be representable as static C values, there
10147db96d56Sopenharmony_ciare many restrictions on legal expressions.  Here's a list of Python features
10157db96d56Sopenharmony_ciyou're not permitted to use:
10167db96d56Sopenharmony_ci
10177db96d56Sopenharmony_ci* Function calls.
10187db96d56Sopenharmony_ci* Inline if statements (``3 if foo else 5``).
10197db96d56Sopenharmony_ci* Automatic sequence unpacking (``*[1, 2, 3]``).
10207db96d56Sopenharmony_ci* List/set/dict comprehensions and generator expressions.
10217db96d56Sopenharmony_ci* Tuple/list/set/dict literals.
10227db96d56Sopenharmony_ci
10237db96d56Sopenharmony_ci
10247db96d56Sopenharmony_ci
10257db96d56Sopenharmony_ciUsing a return converter
10267db96d56Sopenharmony_ci------------------------
10277db96d56Sopenharmony_ci
10287db96d56Sopenharmony_ciBy default, the impl function Argument Clinic generates for you returns
10297db96d56Sopenharmony_ci:c:type:`PyObject * <PyObject>`.
10307db96d56Sopenharmony_ciBut your C function often computes some C type,
10317db96d56Sopenharmony_cithen converts it into the :c:type:`!PyObject *`
10327db96d56Sopenharmony_ciat the last moment.  Argument Clinic handles converting your inputs from Python types
10337db96d56Sopenharmony_ciinto native C types—why not have it convert your return value from a native C type
10347db96d56Sopenharmony_ciinto a Python type too?
10357db96d56Sopenharmony_ci
10367db96d56Sopenharmony_ciThat's what a "return converter" does.  It changes your impl function to return
10377db96d56Sopenharmony_cisome C type, then adds code to the generated (non-impl) function to handle converting
10387db96d56Sopenharmony_cithat value into the appropriate :c:type:`!PyObject *`.
10397db96d56Sopenharmony_ci
10407db96d56Sopenharmony_ciThe syntax for return converters is similar to that of parameter converters.
10417db96d56Sopenharmony_ciYou specify the return converter like it was a return annotation on the
10427db96d56Sopenharmony_cifunction itself, using ``->`` notation.
10437db96d56Sopenharmony_ci
10447db96d56Sopenharmony_ciFor example:
10457db96d56Sopenharmony_ci
10467db96d56Sopenharmony_ci.. code-block:: c
10477db96d56Sopenharmony_ci
10487db96d56Sopenharmony_ci   /*[clinic input]
10497db96d56Sopenharmony_ci   add -> int
10507db96d56Sopenharmony_ci
10517db96d56Sopenharmony_ci       a: int
10527db96d56Sopenharmony_ci       b: int
10537db96d56Sopenharmony_ci       /
10547db96d56Sopenharmony_ci
10557db96d56Sopenharmony_ci   [clinic start generated code]*/
10567db96d56Sopenharmony_ci
10577db96d56Sopenharmony_ciReturn converters behave much the same as parameter converters;
10587db96d56Sopenharmony_cithey take arguments, the arguments are all keyword-only, and if you're not changing
10597db96d56Sopenharmony_ciany of the default arguments you can omit the parentheses.
10607db96d56Sopenharmony_ci
10617db96d56Sopenharmony_ci(If you use both ``"as"`` *and* a return converter for your function,
10627db96d56Sopenharmony_cithe ``"as"`` should come before the return converter.)
10637db96d56Sopenharmony_ci
10647db96d56Sopenharmony_ciThere's one additional complication when using return converters: how do you
10657db96d56Sopenharmony_ciindicate an error has occurred?  Normally, a function returns a valid (non-``NULL``)
10667db96d56Sopenharmony_cipointer for success, and ``NULL`` for failure.  But if you use an integer return converter,
10677db96d56Sopenharmony_ciall integers are valid.  How can Argument Clinic detect an error?  Its solution: each return
10687db96d56Sopenharmony_ciconverter implicitly looks for a special value that indicates an error.  If you return
10697db96d56Sopenharmony_cithat value, and an error has been set (``PyErr_Occurred()`` returns a true
10707db96d56Sopenharmony_civalue), then the generated code will propagate the error.  Otherwise it will
10717db96d56Sopenharmony_ciencode the value you return like normal.
10727db96d56Sopenharmony_ci
10737db96d56Sopenharmony_ciCurrently Argument Clinic supports only a few return converters:
10747db96d56Sopenharmony_ci
10757db96d56Sopenharmony_ci.. code-block:: none
10767db96d56Sopenharmony_ci
10777db96d56Sopenharmony_ci    bool
10787db96d56Sopenharmony_ci    double
10797db96d56Sopenharmony_ci    float
10807db96d56Sopenharmony_ci    int
10817db96d56Sopenharmony_ci    long
10827db96d56Sopenharmony_ci    Py_ssize_t
10837db96d56Sopenharmony_ci    size_t
10847db96d56Sopenharmony_ci    unsigned int
10857db96d56Sopenharmony_ci    unsigned long
10867db96d56Sopenharmony_ci
10877db96d56Sopenharmony_ciNone of these take parameters.
10887db96d56Sopenharmony_ciFor all of these, return ``-1`` to indicate error.
10897db96d56Sopenharmony_ci
10907db96d56Sopenharmony_ci(There's also an experimental ``NoneType`` converter, which lets you
10917db96d56Sopenharmony_cireturn ``Py_None`` on success or ``NULL`` on failure, without having
10927db96d56Sopenharmony_cito increment the reference count on ``Py_None``.  I'm not sure it adds
10937db96d56Sopenharmony_cienough clarity to be worth using.)
10947db96d56Sopenharmony_ci
10957db96d56Sopenharmony_ciTo see all the return converters Argument Clinic supports, along with
10967db96d56Sopenharmony_citheir parameters (if any),
10977db96d56Sopenharmony_cijust run ``Tools/clinic/clinic.py --converters`` for the full list.
10987db96d56Sopenharmony_ci
10997db96d56Sopenharmony_ci
11007db96d56Sopenharmony_ciCloning existing functions
11017db96d56Sopenharmony_ci--------------------------
11027db96d56Sopenharmony_ci
11037db96d56Sopenharmony_ciIf you have a number of functions that look similar, you may be able to
11047db96d56Sopenharmony_ciuse Clinic's "clone" feature.  When you clone an existing function,
11057db96d56Sopenharmony_ciyou reuse:
11067db96d56Sopenharmony_ci
11077db96d56Sopenharmony_ci* its parameters, including
11087db96d56Sopenharmony_ci
11097db96d56Sopenharmony_ci  * their names,
11107db96d56Sopenharmony_ci
11117db96d56Sopenharmony_ci  * their converters, with all parameters,
11127db96d56Sopenharmony_ci
11137db96d56Sopenharmony_ci  * their default values,
11147db96d56Sopenharmony_ci
11157db96d56Sopenharmony_ci  * their per-parameter docstrings,
11167db96d56Sopenharmony_ci
11177db96d56Sopenharmony_ci  * their *kind* (whether they're positional only,
11187db96d56Sopenharmony_ci    positional or keyword, or keyword only), and
11197db96d56Sopenharmony_ci
11207db96d56Sopenharmony_ci* its return converter.
11217db96d56Sopenharmony_ci
11227db96d56Sopenharmony_ciThe only thing not copied from the original function is its docstring;
11237db96d56Sopenharmony_cithe syntax allows you to specify a new docstring.
11247db96d56Sopenharmony_ci
11257db96d56Sopenharmony_ciHere's the syntax for cloning a function::
11267db96d56Sopenharmony_ci
11277db96d56Sopenharmony_ci    /*[clinic input]
11287db96d56Sopenharmony_ci    module.class.new_function [as c_basename] = module.class.existing_function
11297db96d56Sopenharmony_ci
11307db96d56Sopenharmony_ci    Docstring for new_function goes here.
11317db96d56Sopenharmony_ci    [clinic start generated code]*/
11327db96d56Sopenharmony_ci
11337db96d56Sopenharmony_ci(The functions can be in different modules or classes.  I wrote
11347db96d56Sopenharmony_ci``module.class`` in the sample just to illustrate that you must
11357db96d56Sopenharmony_ciuse the full path to *both* functions.)
11367db96d56Sopenharmony_ci
11377db96d56Sopenharmony_ciSorry, there's no syntax for partially cloning a function, or cloning a function
11387db96d56Sopenharmony_cithen modifying it.  Cloning is an all-or nothing proposition.
11397db96d56Sopenharmony_ci
11407db96d56Sopenharmony_ciAlso, the function you are cloning from must have been previously defined
11417db96d56Sopenharmony_ciin the current file.
11427db96d56Sopenharmony_ci
11437db96d56Sopenharmony_ciCalling Python code
11447db96d56Sopenharmony_ci-------------------
11457db96d56Sopenharmony_ci
11467db96d56Sopenharmony_ciThe rest of the advanced topics require you to write Python code
11477db96d56Sopenharmony_ciwhich lives inside your C file and modifies Argument Clinic's
11487db96d56Sopenharmony_ciruntime state.  This is simple: you simply define a Python block.
11497db96d56Sopenharmony_ci
11507db96d56Sopenharmony_ciA Python block uses different delimiter lines than an Argument
11517db96d56Sopenharmony_ciClinic function block.  It looks like this::
11527db96d56Sopenharmony_ci
11537db96d56Sopenharmony_ci    /*[python input]
11547db96d56Sopenharmony_ci    # python code goes here
11557db96d56Sopenharmony_ci    [python start generated code]*/
11567db96d56Sopenharmony_ci
11577db96d56Sopenharmony_ciAll the code inside the Python block is executed at the
11587db96d56Sopenharmony_citime it's parsed.  All text written to stdout inside the block
11597db96d56Sopenharmony_ciis redirected into the "output" after the block.
11607db96d56Sopenharmony_ci
11617db96d56Sopenharmony_ciAs an example, here's a Python block that adds a static integer
11627db96d56Sopenharmony_civariable to the C code::
11637db96d56Sopenharmony_ci
11647db96d56Sopenharmony_ci    /*[python input]
11657db96d56Sopenharmony_ci    print('static int __ignored_unused_variable__ = 0;')
11667db96d56Sopenharmony_ci    [python start generated code]*/
11677db96d56Sopenharmony_ci    static int __ignored_unused_variable__ = 0;
11687db96d56Sopenharmony_ci    /*[python checksum:...]*/
11697db96d56Sopenharmony_ci
11707db96d56Sopenharmony_ci
11717db96d56Sopenharmony_ciUsing a "self converter"
11727db96d56Sopenharmony_ci------------------------
11737db96d56Sopenharmony_ci
11747db96d56Sopenharmony_ciArgument Clinic automatically adds a "self" parameter for you
11757db96d56Sopenharmony_ciusing a default converter.  It automatically sets the ``type``
11767db96d56Sopenharmony_ciof this parameter to the "pointer to an instance" you specified
11777db96d56Sopenharmony_ciwhen you declared the type.  However, you can override
11787db96d56Sopenharmony_ciArgument Clinic's converter and specify one yourself.
11797db96d56Sopenharmony_ciJust add your own ``self`` parameter as the first parameter in a
11807db96d56Sopenharmony_ciblock, and ensure that its converter is an instance of
11817db96d56Sopenharmony_ci``self_converter`` or a subclass thereof.
11827db96d56Sopenharmony_ci
11837db96d56Sopenharmony_ciWhat's the point?  This lets you override the type of ``self``,
11847db96d56Sopenharmony_cior give it a different default name.
11857db96d56Sopenharmony_ci
11867db96d56Sopenharmony_ciHow do you specify the custom type you want to cast ``self`` to?
11877db96d56Sopenharmony_ciIf you only have one or two functions with the same type for ``self``,
11887db96d56Sopenharmony_ciyou can directly use Argument Clinic's existing ``self`` converter,
11897db96d56Sopenharmony_cipassing in the type you want to use as the ``type`` parameter::
11907db96d56Sopenharmony_ci
11917db96d56Sopenharmony_ci    /*[clinic input]
11927db96d56Sopenharmony_ci
11937db96d56Sopenharmony_ci    _pickle.Pickler.dump
11947db96d56Sopenharmony_ci
11957db96d56Sopenharmony_ci      self: self(type="PicklerObject *")
11967db96d56Sopenharmony_ci      obj: object
11977db96d56Sopenharmony_ci      /
11987db96d56Sopenharmony_ci
11997db96d56Sopenharmony_ci    Write a pickled representation of the given object to the open file.
12007db96d56Sopenharmony_ci    [clinic start generated code]*/
12017db96d56Sopenharmony_ci
12027db96d56Sopenharmony_ciOn the other hand, if you have a lot of functions that will use the same
12037db96d56Sopenharmony_citype for ``self``, it's best to create your own converter, subclassing
12047db96d56Sopenharmony_ci``self_converter`` but overwriting the ``type`` member::
12057db96d56Sopenharmony_ci
12067db96d56Sopenharmony_ci    /*[python input]
12077db96d56Sopenharmony_ci    class PicklerObject_converter(self_converter):
12087db96d56Sopenharmony_ci        type = "PicklerObject *"
12097db96d56Sopenharmony_ci    [python start generated code]*/
12107db96d56Sopenharmony_ci
12117db96d56Sopenharmony_ci    /*[clinic input]
12127db96d56Sopenharmony_ci
12137db96d56Sopenharmony_ci    _pickle.Pickler.dump
12147db96d56Sopenharmony_ci
12157db96d56Sopenharmony_ci      self: PicklerObject
12167db96d56Sopenharmony_ci      obj: object
12177db96d56Sopenharmony_ci      /
12187db96d56Sopenharmony_ci
12197db96d56Sopenharmony_ci    Write a pickled representation of the given object to the open file.
12207db96d56Sopenharmony_ci    [clinic start generated code]*/
12217db96d56Sopenharmony_ci
12227db96d56Sopenharmony_ci
12237db96d56Sopenharmony_ciUsing a "defining class" converter
12247db96d56Sopenharmony_ci----------------------------------
12257db96d56Sopenharmony_ci
12267db96d56Sopenharmony_ciArgument Clinic facilitates gaining access to the defining class of a method.
12277db96d56Sopenharmony_ciThis is useful for :ref:`heap type <heap-types>` methods that need to fetch
12287db96d56Sopenharmony_cimodule level state.  Use :c:func:`PyType_FromModuleAndSpec` to associate a new
12297db96d56Sopenharmony_ciheap type with a module.  You can now use :c:func:`PyType_GetModuleState` on
12307db96d56Sopenharmony_cithe defining class to fetch the module state, for example from a module method.
12317db96d56Sopenharmony_ci
12327db96d56Sopenharmony_ciExample from ``Modules/zlibmodule.c``.  First, ``defining_class`` is added to
12337db96d56Sopenharmony_cithe clinic input::
12347db96d56Sopenharmony_ci
12357db96d56Sopenharmony_ci    /*[clinic input]
12367db96d56Sopenharmony_ci    zlib.Compress.compress
12377db96d56Sopenharmony_ci
12387db96d56Sopenharmony_ci      cls: defining_class
12397db96d56Sopenharmony_ci      data: Py_buffer
12407db96d56Sopenharmony_ci        Binary data to be compressed.
12417db96d56Sopenharmony_ci      /
12427db96d56Sopenharmony_ci
12437db96d56Sopenharmony_ci
12447db96d56Sopenharmony_ciAfter running the Argument Clinic tool, the following function signature is
12457db96d56Sopenharmony_cigenerated::
12467db96d56Sopenharmony_ci
12477db96d56Sopenharmony_ci    /*[clinic start generated code]*/
12487db96d56Sopenharmony_ci    static PyObject *
12497db96d56Sopenharmony_ci    zlib_Compress_compress_impl(compobject *self, PyTypeObject *cls,
12507db96d56Sopenharmony_ci                                Py_buffer *data)
12517db96d56Sopenharmony_ci    /*[clinic end generated code: output=6731b3f0ff357ca6 input=04d00f65ab01d260]*/
12527db96d56Sopenharmony_ci
12537db96d56Sopenharmony_ci
12547db96d56Sopenharmony_ciThe following code can now use ``PyType_GetModuleState(cls)`` to fetch the
12557db96d56Sopenharmony_cimodule state::
12567db96d56Sopenharmony_ci
12577db96d56Sopenharmony_ci    zlibstate *state = PyType_GetModuleState(cls);
12587db96d56Sopenharmony_ci
12597db96d56Sopenharmony_ci
12607db96d56Sopenharmony_ciEach method may only have one argument using this converter, and it must appear
12617db96d56Sopenharmony_ciafter ``self``, or, if ``self`` is not used, as the first argument.  The argument
12627db96d56Sopenharmony_ciwill be of type ``PyTypeObject *``.  The argument will not appear in the
12637db96d56Sopenharmony_ci``__text_signature__``.
12647db96d56Sopenharmony_ci
12657db96d56Sopenharmony_ciThe ``defining_class`` converter is not compatible with ``__init__`` and ``__new__``
12667db96d56Sopenharmony_cimethods, which cannot use the ``METH_METHOD`` convention.
12677db96d56Sopenharmony_ci
12687db96d56Sopenharmony_ciIt is not possible to use ``defining_class`` with slot methods.  In order to
12697db96d56Sopenharmony_cifetch the module state from such methods, use :c:func:`PyType_GetModuleByDef`
12707db96d56Sopenharmony_cito look up the module and then :c:func:`PyModule_GetState` to fetch the module
12717db96d56Sopenharmony_cistate.  Example from the ``setattro`` slot method in
12727db96d56Sopenharmony_ci``Modules/_threadmodule.c``::
12737db96d56Sopenharmony_ci
12747db96d56Sopenharmony_ci    static int
12757db96d56Sopenharmony_ci    local_setattro(localobject *self, PyObject *name, PyObject *v)
12767db96d56Sopenharmony_ci    {
12777db96d56Sopenharmony_ci        PyObject *module = PyType_GetModuleByDef(Py_TYPE(self), &thread_module);
12787db96d56Sopenharmony_ci        thread_module_state *state = get_thread_state(module);
12797db96d56Sopenharmony_ci        ...
12807db96d56Sopenharmony_ci    }
12817db96d56Sopenharmony_ci
12827db96d56Sopenharmony_ci
12837db96d56Sopenharmony_ciSee also :pep:`573`.
12847db96d56Sopenharmony_ci
12857db96d56Sopenharmony_ci
12867db96d56Sopenharmony_ciWriting a custom converter
12877db96d56Sopenharmony_ci--------------------------
12887db96d56Sopenharmony_ci
12897db96d56Sopenharmony_ciAs we hinted at in the previous section... you can write your own converters!
12907db96d56Sopenharmony_ciA converter is simply a Python class that inherits from ``CConverter``.
12917db96d56Sopenharmony_ciThe main purpose of a custom converter is if you have a parameter using
12927db96d56Sopenharmony_cithe ``O&`` format unit—parsing this parameter means calling
12937db96d56Sopenharmony_cia :c:func:`PyArg_ParseTuple` "converter function".
12947db96d56Sopenharmony_ci
12957db96d56Sopenharmony_ciYour converter class should be named ``*something*_converter``.
12967db96d56Sopenharmony_ciIf the name follows this convention, then your converter class
12977db96d56Sopenharmony_ciwill be automatically registered with Argument Clinic; its name
12987db96d56Sopenharmony_ciwill be the name of your class with the ``_converter`` suffix
12997db96d56Sopenharmony_cistripped off.  (This is accomplished with a metaclass.)
13007db96d56Sopenharmony_ci
13017db96d56Sopenharmony_ciYou shouldn't subclass ``CConverter.__init__``.  Instead, you should
13027db96d56Sopenharmony_ciwrite a ``converter_init()`` function.  ``converter_init()``
13037db96d56Sopenharmony_cialways accepts a ``self`` parameter; after that, all additional
13047db96d56Sopenharmony_ciparameters *must* be keyword-only.  Any arguments passed in to
13057db96d56Sopenharmony_cithe converter in Argument Clinic will be passed along to your
13067db96d56Sopenharmony_ci``converter_init()``.
13077db96d56Sopenharmony_ci
13087db96d56Sopenharmony_ciThere are some additional members of ``CConverter`` you may wish
13097db96d56Sopenharmony_cito specify in your subclass.  Here's the current list:
13107db96d56Sopenharmony_ci
13117db96d56Sopenharmony_ci``type``
13127db96d56Sopenharmony_ci    The C type to use for this variable.
13137db96d56Sopenharmony_ci    ``type`` should be a Python string specifying the type, e.g. ``int``.
13147db96d56Sopenharmony_ci    If this is a pointer type, the type string should end with ``' *'``.
13157db96d56Sopenharmony_ci
13167db96d56Sopenharmony_ci``default``
13177db96d56Sopenharmony_ci    The Python default value for this parameter, as a Python value.
13187db96d56Sopenharmony_ci    Or the magic value ``unspecified`` if there is no default.
13197db96d56Sopenharmony_ci
13207db96d56Sopenharmony_ci``py_default``
13217db96d56Sopenharmony_ci    ``default`` as it should appear in Python code,
13227db96d56Sopenharmony_ci    as a string.
13237db96d56Sopenharmony_ci    Or ``None`` if there is no default.
13247db96d56Sopenharmony_ci
13257db96d56Sopenharmony_ci``c_default``
13267db96d56Sopenharmony_ci    ``default`` as it should appear in C code,
13277db96d56Sopenharmony_ci    as a string.
13287db96d56Sopenharmony_ci    Or ``None`` if there is no default.
13297db96d56Sopenharmony_ci
13307db96d56Sopenharmony_ci``c_ignored_default``
13317db96d56Sopenharmony_ci    The default value used to initialize the C variable when
13327db96d56Sopenharmony_ci    there is no default, but not specifying a default may
13337db96d56Sopenharmony_ci    result in an "uninitialized variable" warning.  This can
13347db96d56Sopenharmony_ci    easily happen when using option groups—although
13357db96d56Sopenharmony_ci    properly written code will never actually use this value,
13367db96d56Sopenharmony_ci    the variable does get passed in to the impl, and the
13377db96d56Sopenharmony_ci    C compiler will complain about the "use" of the
13387db96d56Sopenharmony_ci    uninitialized value.  This value should always be a
13397db96d56Sopenharmony_ci    non-empty string.
13407db96d56Sopenharmony_ci
13417db96d56Sopenharmony_ci``converter``
13427db96d56Sopenharmony_ci    The name of the C converter function, as a string.
13437db96d56Sopenharmony_ci
13447db96d56Sopenharmony_ci``impl_by_reference``
13457db96d56Sopenharmony_ci    A boolean value.  If true,
13467db96d56Sopenharmony_ci    Argument Clinic will add a ``&`` in front of the name of
13477db96d56Sopenharmony_ci    the variable when passing it into the impl function.
13487db96d56Sopenharmony_ci
13497db96d56Sopenharmony_ci``parse_by_reference``
13507db96d56Sopenharmony_ci    A boolean value.  If true,
13517db96d56Sopenharmony_ci    Argument Clinic will add a ``&`` in front of the name of
13527db96d56Sopenharmony_ci    the variable when passing it into :c:func:`PyArg_ParseTuple`.
13537db96d56Sopenharmony_ci
13547db96d56Sopenharmony_ci
13557db96d56Sopenharmony_ciHere's the simplest example of a custom converter, from ``Modules/zlibmodule.c``::
13567db96d56Sopenharmony_ci
13577db96d56Sopenharmony_ci    /*[python input]
13587db96d56Sopenharmony_ci
13597db96d56Sopenharmony_ci    class ssize_t_converter(CConverter):
13607db96d56Sopenharmony_ci        type = 'Py_ssize_t'
13617db96d56Sopenharmony_ci        converter = 'ssize_t_converter'
13627db96d56Sopenharmony_ci
13637db96d56Sopenharmony_ci    [python start generated code]*/
13647db96d56Sopenharmony_ci    /*[python end generated code: output=da39a3ee5e6b4b0d input=35521e4e733823c7]*/
13657db96d56Sopenharmony_ci
13667db96d56Sopenharmony_ciThis block adds a converter to Argument Clinic named ``ssize_t``.  Parameters
13677db96d56Sopenharmony_cideclared as ``ssize_t`` will be declared as type :c:type:`Py_ssize_t`, and will
13687db96d56Sopenharmony_cibe parsed by the ``'O&'`` format unit, which will call the
13697db96d56Sopenharmony_ci``ssize_t_converter`` converter function.  ``ssize_t`` variables
13707db96d56Sopenharmony_ciautomatically support default values.
13717db96d56Sopenharmony_ci
13727db96d56Sopenharmony_ciMore sophisticated custom converters can insert custom C code to
13737db96d56Sopenharmony_cihandle initialization and cleanup.
13747db96d56Sopenharmony_ciYou can see more examples of custom converters in the CPython
13757db96d56Sopenharmony_cisource tree; grep the C files for the string ``CConverter``.
13767db96d56Sopenharmony_ci
13777db96d56Sopenharmony_ciWriting a custom return converter
13787db96d56Sopenharmony_ci---------------------------------
13797db96d56Sopenharmony_ci
13807db96d56Sopenharmony_ciWriting a custom return converter is much like writing
13817db96d56Sopenharmony_cia custom converter.  Except it's somewhat simpler, because return
13827db96d56Sopenharmony_ciconverters are themselves much simpler.
13837db96d56Sopenharmony_ci
13847db96d56Sopenharmony_ciReturn converters must subclass ``CReturnConverter``.
13857db96d56Sopenharmony_ciThere are no examples yet of custom return converters,
13867db96d56Sopenharmony_cibecause they are not widely used yet.  If you wish to
13877db96d56Sopenharmony_ciwrite your own return converter, please read ``Tools/clinic/clinic.py``,
13887db96d56Sopenharmony_cispecifically the implementation of ``CReturnConverter`` and
13897db96d56Sopenharmony_ciall its subclasses.
13907db96d56Sopenharmony_ci
13917db96d56Sopenharmony_ciMETH_O and METH_NOARGS
13927db96d56Sopenharmony_ci----------------------------------------------
13937db96d56Sopenharmony_ci
13947db96d56Sopenharmony_ciTo convert a function using ``METH_O``, make sure the function's
13957db96d56Sopenharmony_cisingle argument is using the ``object`` converter, and mark the
13967db96d56Sopenharmony_ciarguments as positional-only::
13977db96d56Sopenharmony_ci
13987db96d56Sopenharmony_ci    /*[clinic input]
13997db96d56Sopenharmony_ci    meth_o_sample
14007db96d56Sopenharmony_ci
14017db96d56Sopenharmony_ci         argument: object
14027db96d56Sopenharmony_ci         /
14037db96d56Sopenharmony_ci    [clinic start generated code]*/
14047db96d56Sopenharmony_ci
14057db96d56Sopenharmony_ci
14067db96d56Sopenharmony_ciTo convert a function using ``METH_NOARGS``, just don't specify
14077db96d56Sopenharmony_ciany arguments.
14087db96d56Sopenharmony_ci
14097db96d56Sopenharmony_ciYou can still use a self converter, a return converter, and specify
14107db96d56Sopenharmony_cia ``type`` argument to the object converter for ``METH_O``.
14117db96d56Sopenharmony_ci
14127db96d56Sopenharmony_citp_new and tp_init functions
14137db96d56Sopenharmony_ci----------------------------------------------
14147db96d56Sopenharmony_ci
14157db96d56Sopenharmony_ciYou can convert ``tp_new`` and ``tp_init`` functions.  Just name
14167db96d56Sopenharmony_cithem ``__new__`` or ``__init__`` as appropriate.  Notes:
14177db96d56Sopenharmony_ci
14187db96d56Sopenharmony_ci* The function name generated for ``__new__`` doesn't end in ``__new__``
14197db96d56Sopenharmony_ci  like it would by default.  It's just the name of the class, converted
14207db96d56Sopenharmony_ci  into a valid C identifier.
14217db96d56Sopenharmony_ci
14227db96d56Sopenharmony_ci* No ``PyMethodDef`` ``#define`` is generated for these functions.
14237db96d56Sopenharmony_ci
14247db96d56Sopenharmony_ci* ``__init__`` functions return ``int``, not ``PyObject *``.
14257db96d56Sopenharmony_ci
14267db96d56Sopenharmony_ci* Use the docstring as the class docstring.
14277db96d56Sopenharmony_ci
14287db96d56Sopenharmony_ci* Although ``__new__`` and ``__init__`` functions must always
14297db96d56Sopenharmony_ci  accept both the ``args`` and ``kwargs`` objects, when converting
14307db96d56Sopenharmony_ci  you may specify any signature for these functions that you like.
14317db96d56Sopenharmony_ci  (If your function doesn't support keywords, the parsing function
14327db96d56Sopenharmony_ci  generated will throw an exception if it receives any.)
14337db96d56Sopenharmony_ci
14347db96d56Sopenharmony_ciChanging and redirecting Clinic's output
14357db96d56Sopenharmony_ci----------------------------------------
14367db96d56Sopenharmony_ci
14377db96d56Sopenharmony_ciIt can be inconvenient to have Clinic's output interspersed with
14387db96d56Sopenharmony_ciyour conventional hand-edited C code.  Luckily, Clinic is configurable:
14397db96d56Sopenharmony_ciyou can buffer up its output for printing later (or earlier!), or write
14407db96d56Sopenharmony_ciits output to a separate file.  You can also add a prefix or suffix to
14417db96d56Sopenharmony_cievery line of Clinic's generated output.
14427db96d56Sopenharmony_ci
14437db96d56Sopenharmony_ciWhile changing Clinic's output in this manner can be a boon to readability,
14447db96d56Sopenharmony_ciit may result in Clinic code using types before they are defined, or
14457db96d56Sopenharmony_ciyour code attempting to use Clinic-generated code before it is defined.
14467db96d56Sopenharmony_ciThese problems can be easily solved by rearranging the declarations in your file,
14477db96d56Sopenharmony_cior moving where Clinic's generated code goes.  (This is why the default behavior
14487db96d56Sopenharmony_ciof Clinic is to output everything into the current block; while many people
14497db96d56Sopenharmony_ciconsider this hampers readability, it will never require rearranging your
14507db96d56Sopenharmony_cicode to fix definition-before-use problems.)
14517db96d56Sopenharmony_ci
14527db96d56Sopenharmony_ciLet's start with defining some terminology:
14537db96d56Sopenharmony_ci
14547db96d56Sopenharmony_ci*field*
14557db96d56Sopenharmony_ci  A field, in this context, is a subsection of Clinic's output.
14567db96d56Sopenharmony_ci  For example, the ``#define`` for the ``PyMethodDef`` structure
14577db96d56Sopenharmony_ci  is a field, called ``methoddef_define``.  Clinic has seven
14587db96d56Sopenharmony_ci  different fields it can output per function definition:
14597db96d56Sopenharmony_ci
14607db96d56Sopenharmony_ci  .. code-block:: none
14617db96d56Sopenharmony_ci
14627db96d56Sopenharmony_ci      docstring_prototype
14637db96d56Sopenharmony_ci      docstring_definition
14647db96d56Sopenharmony_ci      methoddef_define
14657db96d56Sopenharmony_ci      impl_prototype
14667db96d56Sopenharmony_ci      parser_prototype
14677db96d56Sopenharmony_ci      parser_definition
14687db96d56Sopenharmony_ci      impl_definition
14697db96d56Sopenharmony_ci
14707db96d56Sopenharmony_ci  All the names are of the form ``"<a>_<b>"``,
14717db96d56Sopenharmony_ci  where ``"<a>"`` is the semantic object represented (the parsing function,
14727db96d56Sopenharmony_ci  the impl function, the docstring, or the methoddef structure) and ``"<b>"``
14737db96d56Sopenharmony_ci  represents what kind of statement the field is.  Field names that end in
14747db96d56Sopenharmony_ci  ``"_prototype"``
14757db96d56Sopenharmony_ci  represent forward declarations of that thing, without the actual body/data
14767db96d56Sopenharmony_ci  of the thing; field names that end in ``"_definition"`` represent the actual
14777db96d56Sopenharmony_ci  definition of the thing, with the body/data of the thing.  (``"methoddef"``
14787db96d56Sopenharmony_ci  is special, it's the only one that ends with ``"_define"``, representing that
14797db96d56Sopenharmony_ci  it's a preprocessor #define.)
14807db96d56Sopenharmony_ci
14817db96d56Sopenharmony_ci*destination*
14827db96d56Sopenharmony_ci  A destination is a place Clinic can write output to.  There are
14837db96d56Sopenharmony_ci  five built-in destinations:
14847db96d56Sopenharmony_ci
14857db96d56Sopenharmony_ci  ``block``
14867db96d56Sopenharmony_ci    The default destination: printed in the output section of
14877db96d56Sopenharmony_ci    the current Clinic block.
14887db96d56Sopenharmony_ci
14897db96d56Sopenharmony_ci  ``buffer``
14907db96d56Sopenharmony_ci    A text buffer where you can save text for later.  Text sent
14917db96d56Sopenharmony_ci    here is appended to the end of any existing text.  It's an
14927db96d56Sopenharmony_ci    error to have any text left in the buffer when Clinic finishes
14937db96d56Sopenharmony_ci    processing a file.
14947db96d56Sopenharmony_ci
14957db96d56Sopenharmony_ci  ``file``
14967db96d56Sopenharmony_ci    A separate "clinic file" that will be created automatically by Clinic.
14977db96d56Sopenharmony_ci    The filename chosen for the file is ``{basename}.clinic{extension}``,
14987db96d56Sopenharmony_ci    where ``basename`` and ``extension`` were assigned the output
14997db96d56Sopenharmony_ci    from ``os.path.splitext()`` run on the current file.  (Example:
15007db96d56Sopenharmony_ci    the ``file`` destination for ``_pickle.c`` would be written to
15017db96d56Sopenharmony_ci    ``_pickle.clinic.c``.)
15027db96d56Sopenharmony_ci
15037db96d56Sopenharmony_ci    **Important: When using a** ``file`` **destination, you**
15047db96d56Sopenharmony_ci    *must check in* **the generated file!**
15057db96d56Sopenharmony_ci
15067db96d56Sopenharmony_ci  ``two-pass``
15077db96d56Sopenharmony_ci    A buffer like ``buffer``.  However, a two-pass buffer can only
15087db96d56Sopenharmony_ci    be dumped once, and it prints out all text sent to it during
15097db96d56Sopenharmony_ci    all processing, even from Clinic blocks *after* the dumping point.
15107db96d56Sopenharmony_ci
15117db96d56Sopenharmony_ci  ``suppress``
15127db96d56Sopenharmony_ci    The text is suppressed—thrown away.
15137db96d56Sopenharmony_ci
15147db96d56Sopenharmony_ci
15157db96d56Sopenharmony_ciClinic defines five new directives that let you reconfigure its output.
15167db96d56Sopenharmony_ci
15177db96d56Sopenharmony_ciThe first new directive is ``dump``:
15187db96d56Sopenharmony_ci
15197db96d56Sopenharmony_ci.. code-block:: none
15207db96d56Sopenharmony_ci
15217db96d56Sopenharmony_ci   dump <destination>
15227db96d56Sopenharmony_ci
15237db96d56Sopenharmony_ciThis dumps the current contents of the named destination into the output of
15247db96d56Sopenharmony_cithe current block, and empties it.  This only works with ``buffer`` and
15257db96d56Sopenharmony_ci``two-pass`` destinations.
15267db96d56Sopenharmony_ci
15277db96d56Sopenharmony_ciThe second new directive is ``output``.  The most basic form of ``output``
15287db96d56Sopenharmony_ciis like this:
15297db96d56Sopenharmony_ci
15307db96d56Sopenharmony_ci.. code-block:: none
15317db96d56Sopenharmony_ci
15327db96d56Sopenharmony_ci    output <field> <destination>
15337db96d56Sopenharmony_ci
15347db96d56Sopenharmony_ciThis tells Clinic to output *field* to *destination*.  ``output`` also
15357db96d56Sopenharmony_cisupports a special meta-destination, called ``everything``, which tells
15367db96d56Sopenharmony_ciClinic to output *all* fields to that *destination*.
15377db96d56Sopenharmony_ci
15387db96d56Sopenharmony_ci``output`` has a number of other functions:
15397db96d56Sopenharmony_ci
15407db96d56Sopenharmony_ci.. code-block:: none
15417db96d56Sopenharmony_ci
15427db96d56Sopenharmony_ci    output push
15437db96d56Sopenharmony_ci    output pop
15447db96d56Sopenharmony_ci    output preset <preset>
15457db96d56Sopenharmony_ci
15467db96d56Sopenharmony_ci
15477db96d56Sopenharmony_ci``output push`` and ``output pop`` allow you to push and pop
15487db96d56Sopenharmony_ciconfigurations on an internal configuration stack, so that you
15497db96d56Sopenharmony_cican temporarily modify the output configuration, then easily restore
15507db96d56Sopenharmony_cithe previous configuration.  Simply push before your change to save
15517db96d56Sopenharmony_cithe current configuration, then pop when you wish to restore the
15527db96d56Sopenharmony_ciprevious configuration.
15537db96d56Sopenharmony_ci
15547db96d56Sopenharmony_ci``output preset`` sets Clinic's output to one of several built-in
15557db96d56Sopenharmony_cipreset configurations, as follows:
15567db96d56Sopenharmony_ci
15577db96d56Sopenharmony_ci  ``block``
15587db96d56Sopenharmony_ci    Clinic's original starting configuration.  Writes everything
15597db96d56Sopenharmony_ci    immediately after the input block.
15607db96d56Sopenharmony_ci
15617db96d56Sopenharmony_ci    Suppress the ``parser_prototype``
15627db96d56Sopenharmony_ci    and ``docstring_prototype``, write everything else to ``block``.
15637db96d56Sopenharmony_ci
15647db96d56Sopenharmony_ci  ``file``
15657db96d56Sopenharmony_ci    Designed to write everything to the "clinic file" that it can.
15667db96d56Sopenharmony_ci    You then ``#include`` this file near the top of your file.
15677db96d56Sopenharmony_ci    You may need to rearrange your file to make this work, though
15687db96d56Sopenharmony_ci    usually this just means creating forward declarations for various
15697db96d56Sopenharmony_ci    ``typedef`` and ``PyTypeObject`` definitions.
15707db96d56Sopenharmony_ci
15717db96d56Sopenharmony_ci    Suppress the ``parser_prototype``
15727db96d56Sopenharmony_ci    and ``docstring_prototype``, write the ``impl_definition`` to
15737db96d56Sopenharmony_ci    ``block``, and write everything else to ``file``.
15747db96d56Sopenharmony_ci
15757db96d56Sopenharmony_ci    The default filename is ``"{dirname}/clinic/{basename}.h"``.
15767db96d56Sopenharmony_ci
15777db96d56Sopenharmony_ci  ``buffer``
15787db96d56Sopenharmony_ci    Save up most of the output from Clinic, to be written into
15797db96d56Sopenharmony_ci    your file near the end.  For Python files implementing modules
15807db96d56Sopenharmony_ci    or builtin types, it's recommended that you dump the buffer
15817db96d56Sopenharmony_ci    just above the static structures for your module or
15827db96d56Sopenharmony_ci    builtin type; these are normally very near the end.  Using
15837db96d56Sopenharmony_ci    ``buffer`` may require even more editing than ``file``, if
15847db96d56Sopenharmony_ci    your file has static ``PyMethodDef`` arrays defined in the
15857db96d56Sopenharmony_ci    middle of the file.
15867db96d56Sopenharmony_ci
15877db96d56Sopenharmony_ci    Suppress the ``parser_prototype``, ``impl_prototype``,
15887db96d56Sopenharmony_ci    and ``docstring_prototype``, write the ``impl_definition`` to
15897db96d56Sopenharmony_ci    ``block``, and write everything else to ``file``.
15907db96d56Sopenharmony_ci
15917db96d56Sopenharmony_ci  ``two-pass``
15927db96d56Sopenharmony_ci    Similar to the ``buffer`` preset, but writes forward declarations to
15937db96d56Sopenharmony_ci    the ``two-pass`` buffer, and definitions to the ``buffer``.
15947db96d56Sopenharmony_ci    This is similar to the ``buffer`` preset, but may require
15957db96d56Sopenharmony_ci    less editing than ``buffer``.  Dump the ``two-pass`` buffer
15967db96d56Sopenharmony_ci    near the top of your file, and dump the ``buffer`` near
15977db96d56Sopenharmony_ci    the end just like you would when using the ``buffer`` preset.
15987db96d56Sopenharmony_ci
15997db96d56Sopenharmony_ci    Suppresses the ``impl_prototype``, write the ``impl_definition``
16007db96d56Sopenharmony_ci    to ``block``, write ``docstring_prototype``, ``methoddef_define``,
16017db96d56Sopenharmony_ci    and ``parser_prototype`` to ``two-pass``, write everything else
16027db96d56Sopenharmony_ci    to ``buffer``.
16037db96d56Sopenharmony_ci
16047db96d56Sopenharmony_ci  ``partial-buffer``
16057db96d56Sopenharmony_ci    Similar to the ``buffer`` preset, but writes more things to ``block``,
16067db96d56Sopenharmony_ci    only writing the really big chunks of generated code to ``buffer``.
16077db96d56Sopenharmony_ci    This avoids the definition-before-use problem of ``buffer`` completely,
16087db96d56Sopenharmony_ci    at the small cost of having slightly more stuff in the block's output.
16097db96d56Sopenharmony_ci    Dump the ``buffer`` near the end, just like you would when using
16107db96d56Sopenharmony_ci    the ``buffer`` preset.
16117db96d56Sopenharmony_ci
16127db96d56Sopenharmony_ci    Suppresses the ``impl_prototype``, write the ``docstring_definition``
16137db96d56Sopenharmony_ci    and ``parser_definition`` to ``buffer``, write everything else to ``block``.
16147db96d56Sopenharmony_ci
16157db96d56Sopenharmony_ciThe third new directive is ``destination``:
16167db96d56Sopenharmony_ci
16177db96d56Sopenharmony_ci.. code-block:: none
16187db96d56Sopenharmony_ci
16197db96d56Sopenharmony_ci    destination <name> <command> [...]
16207db96d56Sopenharmony_ci
16217db96d56Sopenharmony_ciThis performs an operation on the destination named ``name``.
16227db96d56Sopenharmony_ci
16237db96d56Sopenharmony_ciThere are two defined subcommands: ``new`` and ``clear``.
16247db96d56Sopenharmony_ci
16257db96d56Sopenharmony_ciThe ``new`` subcommand works like this:
16267db96d56Sopenharmony_ci
16277db96d56Sopenharmony_ci.. code-block:: none
16287db96d56Sopenharmony_ci
16297db96d56Sopenharmony_ci    destination <name> new <type>
16307db96d56Sopenharmony_ci
16317db96d56Sopenharmony_ciThis creates a new destination with name ``<name>`` and type ``<type>``.
16327db96d56Sopenharmony_ci
16337db96d56Sopenharmony_ciThere are five destination types:
16347db96d56Sopenharmony_ci
16357db96d56Sopenharmony_ci    ``suppress``
16367db96d56Sopenharmony_ci        Throws the text away.
16377db96d56Sopenharmony_ci
16387db96d56Sopenharmony_ci    ``block``
16397db96d56Sopenharmony_ci        Writes the text to the current block.  This is what Clinic
16407db96d56Sopenharmony_ci        originally did.
16417db96d56Sopenharmony_ci
16427db96d56Sopenharmony_ci    ``buffer``
16437db96d56Sopenharmony_ci        A simple text buffer, like the "buffer" builtin destination above.
16447db96d56Sopenharmony_ci
16457db96d56Sopenharmony_ci    ``file``
16467db96d56Sopenharmony_ci        A text file.  The file destination takes an extra argument,
16477db96d56Sopenharmony_ci        a template to use for building the filename, like so:
16487db96d56Sopenharmony_ci
16497db96d56Sopenharmony_ci            destination <name> new <type> <file_template>
16507db96d56Sopenharmony_ci
16517db96d56Sopenharmony_ci        The template can use three strings internally that will be replaced
16527db96d56Sopenharmony_ci        by bits of the filename:
16537db96d56Sopenharmony_ci
16547db96d56Sopenharmony_ci            {path}
16557db96d56Sopenharmony_ci                The full path to the file, including directory and full filename.
16567db96d56Sopenharmony_ci            {dirname}
16577db96d56Sopenharmony_ci                The name of the directory the file is in.
16587db96d56Sopenharmony_ci            {basename}
16597db96d56Sopenharmony_ci                Just the name of the file, not including the directory.
16607db96d56Sopenharmony_ci            {basename_root}
16617db96d56Sopenharmony_ci                Basename with the extension clipped off
16627db96d56Sopenharmony_ci                (everything up to but not including the last '.').
16637db96d56Sopenharmony_ci            {basename_extension}
16647db96d56Sopenharmony_ci                The last '.' and everything after it.  If the basename
16657db96d56Sopenharmony_ci                does not contain a period, this will be the empty string.
16667db96d56Sopenharmony_ci
16677db96d56Sopenharmony_ci        If there are no periods in the filename, {basename} and {filename}
16687db96d56Sopenharmony_ci        are the same, and {extension} is empty.  "{basename}{extension}"
16697db96d56Sopenharmony_ci        is always exactly the same as "{filename}"."
16707db96d56Sopenharmony_ci
16717db96d56Sopenharmony_ci    ``two-pass``
16727db96d56Sopenharmony_ci        A two-pass buffer, like the "two-pass" builtin destination above.
16737db96d56Sopenharmony_ci
16747db96d56Sopenharmony_ci
16757db96d56Sopenharmony_ciThe ``clear`` subcommand works like this:
16767db96d56Sopenharmony_ci
16777db96d56Sopenharmony_ci.. code-block:: none
16787db96d56Sopenharmony_ci
16797db96d56Sopenharmony_ci    destination <name> clear
16807db96d56Sopenharmony_ci
16817db96d56Sopenharmony_ciIt removes all the accumulated text up to this point in the destination.
16827db96d56Sopenharmony_ci(I don't know what you'd need this for, but I thought maybe it'd be
16837db96d56Sopenharmony_ciuseful while someone's experimenting.)
16847db96d56Sopenharmony_ci
16857db96d56Sopenharmony_ciThe fourth new directive is ``set``:
16867db96d56Sopenharmony_ci
16877db96d56Sopenharmony_ci.. code-block:: none
16887db96d56Sopenharmony_ci
16897db96d56Sopenharmony_ci    set line_prefix "string"
16907db96d56Sopenharmony_ci    set line_suffix "string"
16917db96d56Sopenharmony_ci
16927db96d56Sopenharmony_ci``set`` lets you set two internal variables in Clinic.
16937db96d56Sopenharmony_ci``line_prefix`` is a string that will be prepended to every line of Clinic's output;
16947db96d56Sopenharmony_ci``line_suffix`` is a string that will be appended to every line of Clinic's output.
16957db96d56Sopenharmony_ci
16967db96d56Sopenharmony_ciBoth of these support two format strings:
16977db96d56Sopenharmony_ci
16987db96d56Sopenharmony_ci  ``{block comment start}``
16997db96d56Sopenharmony_ci    Turns into the string ``/*``, the start-comment text sequence for C files.
17007db96d56Sopenharmony_ci
17017db96d56Sopenharmony_ci  ``{block comment end}``
17027db96d56Sopenharmony_ci    Turns into the string ``*/``, the end-comment text sequence for C files.
17037db96d56Sopenharmony_ci
17047db96d56Sopenharmony_ciThe final new directive is one you shouldn't need to use directly,
17057db96d56Sopenharmony_cicalled ``preserve``:
17067db96d56Sopenharmony_ci
17077db96d56Sopenharmony_ci.. code-block:: none
17087db96d56Sopenharmony_ci
17097db96d56Sopenharmony_ci    preserve
17107db96d56Sopenharmony_ci
17117db96d56Sopenharmony_ciThis tells Clinic that the current contents of the output should be kept, unmodified.
17127db96d56Sopenharmony_ciThis is used internally by Clinic when dumping output into ``file`` files; wrapping
17137db96d56Sopenharmony_ciit in a Clinic block lets Clinic use its existing checksum functionality to ensure
17147db96d56Sopenharmony_cithe file was not modified by hand before it gets overwritten.
17157db96d56Sopenharmony_ci
17167db96d56Sopenharmony_ci
17177db96d56Sopenharmony_ciThe #ifdef trick
17187db96d56Sopenharmony_ci----------------------------------------------
17197db96d56Sopenharmony_ci
17207db96d56Sopenharmony_ciIf you're converting a function that isn't available on all platforms,
17217db96d56Sopenharmony_cithere's a trick you can use to make life a little easier.  The existing
17227db96d56Sopenharmony_cicode probably looks like this::
17237db96d56Sopenharmony_ci
17247db96d56Sopenharmony_ci    #ifdef HAVE_FUNCTIONNAME
17257db96d56Sopenharmony_ci    static module_functionname(...)
17267db96d56Sopenharmony_ci    {
17277db96d56Sopenharmony_ci    ...
17287db96d56Sopenharmony_ci    }
17297db96d56Sopenharmony_ci    #endif /* HAVE_FUNCTIONNAME */
17307db96d56Sopenharmony_ci
17317db96d56Sopenharmony_ciAnd then in the ``PyMethodDef`` structure at the bottom the existing code
17327db96d56Sopenharmony_ciwill have:
17337db96d56Sopenharmony_ci
17347db96d56Sopenharmony_ci.. code-block:: none
17357db96d56Sopenharmony_ci
17367db96d56Sopenharmony_ci    #ifdef HAVE_FUNCTIONNAME
17377db96d56Sopenharmony_ci    {'functionname', ... },
17387db96d56Sopenharmony_ci    #endif /* HAVE_FUNCTIONNAME */
17397db96d56Sopenharmony_ci
17407db96d56Sopenharmony_ciIn this scenario, you should enclose the body of your impl function inside the ``#ifdef``,
17417db96d56Sopenharmony_cilike so::
17427db96d56Sopenharmony_ci
17437db96d56Sopenharmony_ci    #ifdef HAVE_FUNCTIONNAME
17447db96d56Sopenharmony_ci    /*[clinic input]
17457db96d56Sopenharmony_ci    module.functionname
17467db96d56Sopenharmony_ci    ...
17477db96d56Sopenharmony_ci    [clinic start generated code]*/
17487db96d56Sopenharmony_ci    static module_functionname(...)
17497db96d56Sopenharmony_ci    {
17507db96d56Sopenharmony_ci    ...
17517db96d56Sopenharmony_ci    }
17527db96d56Sopenharmony_ci    #endif /* HAVE_FUNCTIONNAME */
17537db96d56Sopenharmony_ci
17547db96d56Sopenharmony_ciThen, remove those three lines from the ``PyMethodDef`` structure,
17557db96d56Sopenharmony_cireplacing them with the macro Argument Clinic generated:
17567db96d56Sopenharmony_ci
17577db96d56Sopenharmony_ci.. code-block:: none
17587db96d56Sopenharmony_ci
17597db96d56Sopenharmony_ci    MODULE_FUNCTIONNAME_METHODDEF
17607db96d56Sopenharmony_ci
17617db96d56Sopenharmony_ci(You can find the real name for this macro inside the generated code.
17627db96d56Sopenharmony_ciOr you can calculate it yourself: it's the name of your function as defined
17637db96d56Sopenharmony_cion the first line of your block, but with periods changed to underscores,
17647db96d56Sopenharmony_ciuppercased, and ``"_METHODDEF"`` added to the end.)
17657db96d56Sopenharmony_ci
17667db96d56Sopenharmony_ciPerhaps you're wondering: what if ``HAVE_FUNCTIONNAME`` isn't defined?
17677db96d56Sopenharmony_ciThe ``MODULE_FUNCTIONNAME_METHODDEF`` macro won't be defined either!
17687db96d56Sopenharmony_ci
17697db96d56Sopenharmony_ciHere's where Argument Clinic gets very clever.  It actually detects that the
17707db96d56Sopenharmony_ciArgument Clinic block might be deactivated by the ``#ifdef``.  When that
17717db96d56Sopenharmony_cihappens, it generates a little extra code that looks like this::
17727db96d56Sopenharmony_ci
17737db96d56Sopenharmony_ci    #ifndef MODULE_FUNCTIONNAME_METHODDEF
17747db96d56Sopenharmony_ci        #define MODULE_FUNCTIONNAME_METHODDEF
17757db96d56Sopenharmony_ci    #endif /* !defined(MODULE_FUNCTIONNAME_METHODDEF) */
17767db96d56Sopenharmony_ci
17777db96d56Sopenharmony_ciThat means the macro always works.  If the function is defined, this turns
17787db96d56Sopenharmony_ciinto the correct structure, including the trailing comma.  If the function is
17797db96d56Sopenharmony_ciundefined, this turns into nothing.
17807db96d56Sopenharmony_ci
17817db96d56Sopenharmony_ciHowever, this causes one ticklish problem: where should Argument Clinic put this
17827db96d56Sopenharmony_ciextra code when using the "block" output preset?  It can't go in the output block,
17837db96d56Sopenharmony_cibecause that could be deactivated by the ``#ifdef``.  (That's the whole point!)
17847db96d56Sopenharmony_ci
17857db96d56Sopenharmony_ciIn this situation, Argument Clinic writes the extra code to the "buffer" destination.
17867db96d56Sopenharmony_ciThis may mean that you get a complaint from Argument Clinic:
17877db96d56Sopenharmony_ci
17887db96d56Sopenharmony_ci.. code-block:: none
17897db96d56Sopenharmony_ci
17907db96d56Sopenharmony_ci    Warning in file "Modules/posixmodule.c" on line 12357:
17917db96d56Sopenharmony_ci    Destination buffer 'buffer' not empty at end of file, emptying.
17927db96d56Sopenharmony_ci
17937db96d56Sopenharmony_ciWhen this happens, just open your file, find the ``dump buffer`` block that
17947db96d56Sopenharmony_ciArgument Clinic added to your file (it'll be at the very bottom), then
17957db96d56Sopenharmony_cimove it above the ``PyMethodDef`` structure where that macro is used.
17967db96d56Sopenharmony_ci
17977db96d56Sopenharmony_ci
17987db96d56Sopenharmony_ci
17997db96d56Sopenharmony_ciUsing Argument Clinic in Python files
18007db96d56Sopenharmony_ci-------------------------------------
18017db96d56Sopenharmony_ci
18027db96d56Sopenharmony_ciIt's actually possible to use Argument Clinic to preprocess Python files.
18037db96d56Sopenharmony_ciThere's no point to using Argument Clinic blocks, of course, as the output
18047db96d56Sopenharmony_ciwouldn't make any sense to the Python interpreter.  But using Argument Clinic
18057db96d56Sopenharmony_cito run Python blocks lets you use Python as a Python preprocessor!
18067db96d56Sopenharmony_ci
18077db96d56Sopenharmony_ciSince Python comments are different from C comments, Argument Clinic
18087db96d56Sopenharmony_ciblocks embedded in Python files look slightly different.  They look like this:
18097db96d56Sopenharmony_ci
18107db96d56Sopenharmony_ci.. code-block:: python3
18117db96d56Sopenharmony_ci
18127db96d56Sopenharmony_ci    #/*[python input]
18137db96d56Sopenharmony_ci    #print("def foo(): pass")
18147db96d56Sopenharmony_ci    #[python start generated code]*/
18157db96d56Sopenharmony_ci    def foo(): pass
18167db96d56Sopenharmony_ci    #/*[python checksum:...]*/
1817