Here are the steps to add a ternary operator to CPython. This article uses Python 3.10. Please refer to here for the explanation of CPython build and file structure.
The Python ternary operators are: In Python, (value when condition is True) comes first, (condition) comes next, and finally (value when condition is False). It is not common for the (condition) to be in the middle in the ternary operator grammar.
(Value when the condition is True) if (conditions) else (conditionsがFalseのときの値)
The modified ternary operator is as follows. (Condition) comes first, then (value when condition is True), and finally (value when condition is False). In C language etc., ternary operators are described in this order.
if (conditions) then (conditionsがTrueのときの値) else (conditionsがFalseのときの値)
Now let's change the Python ternary operator to the one shown in 2.2. The ternary operator already exists in Python. So, you can use this and call the same process when if then else comes. Here, we only change python.gram. There is the following description in L341 of Grammer / python.gram.
Grammer/python.gram
a = disjunction 'if' b=disjunction 'else' c=expression { _Py_IfExp(b, a, c, EXTRA) }
This is a description of the original Python ternary operator. To imitate this, write the modified ternary operator on the line below.
Grammer/python.gram
'if' a = disjunction 'then' b=disjunction 'else' c=expression { _Py_IfExp(a, b, c, EXTRA) }
Here, pay attention to the order of the variables when calling _Py_IfExp. With the above changes
$ make regen-pegen
You can add the ternary operator by executing and rebuilding. Of course, you can also use the original ternary operator syntax.
The ternary operator implemented by the above changes works as follows.
-Exploring large-scale software
This is an experimental site.
-CPython
CPython repository
-24. Changing CPython ’s Grammar
A checklist for adding features to CPython was included to help you understand the structure of CPython.
Recommended Posts