Summary
This example shows how a new keyword, namely
repeat, could be introduced to simplify learning Python by beginners.To do this, we include four different transformations, one of which requires to add some extra variables to the original code. It is done in a way that avoid any conflict with existing variable names.
It also shows how to include some parameters that are passed back to the source transformation.
repeat as a keyword
Let’s begin with an example.
> python -m ideas -a repeat --show
Ideas Console version 0.2.0. [Python version: 3.11.9]
ideas> repeat 3:
... print("Hello")
...
===========Transformed============
for _f6e2a07472364c32866ce473ee705576 in range( 3):
print("Hello")
-----------------------------
Hello
Hello
Hello
As you can see, repeat n, where n is an integer,
is converted into a for loop, with a randomly named
variable, guaranteed not to have a name used for another
object in the program. This works well in practice.
However, suppose we wish to do some repeatable tests,
ensuring that the variable names are always the same
for all tests: we can do this using a ‘callback parameter’.
This is a parameter that is given to the add_hook
function used to create the import hook.
add_hook must use Python dict to pass all required
callback parameters to create_hook, so that they
can be passed back to the function used to transform the code.
Here’s a second example using it.
>>> from ideas.examples import repeat
>>> from ideas.console import start
>>> from ideas import current_state
>>> current_state.show_changes = True
>>> repeat.add_hook(predictable_names=True)
<Ideas import hook: ideas.examples.repeat>
>>> start()
Ideas Console version 0.2.0. [Python version: 3.11.9]
ideas> output = ""
ideas> repeat 4:
... output += "*"
... repeat 3:
... print(output)
...
===========Transformed============
for _1 in range( 4):
output += "*"
for _2 in range( 3):
print(output)
-----------------------------
*
*
*
**
**
**
***
***
***
****
****
****
As you can see, the name of the for loop variables, _1, _2,
are much simpler … and predictable.
In the above example, predictable_names is a
callback parameter.
You will need to have a look at the code for repeat.py to
fully understand how to use such callback parameters in your
own import hooks.
Four different cases
The four constructs supported are:
repeat n:
# code
repeat while condition:
# code
repeat until condition:
# code
repeat forever:
# code