cursed-for
Adding C-style for loops to Python, because you can.
>>> for (i = 0; i < 10; i += 2):
... print(i)
0
2
4
6
8
Installation
pip install cursed-for
Usage
Add the following # coding
comment at the top of the file in which you wish to
curse:
# coding: cursed_for
Then write the cursed for-loops as needed. Check this file for an example.
For an interactive REPL, type cursed-for
in your terminal:
$ cursed-for
Cursed Python REPL, 3.10.4 (main, Apr 2 2022, 09:04:19) [GCC 11.2.0]
>>> x = 10
>>> for (;x > 5;x -= 3):
... print(x)
10
7
But why?
This was made because of a cursed idea I had one night, which I put on twitter:
And although this worked, I didn't like the look of it. But using the methods I used, I was confined by Python's syntax, which really doesn't support the kind of things I'd have liked to do. But then I stumbled upon a couple of packages which gave me exactly the tools I needed to commit this atrocity.
OK, but how is this possible?
I wrote a blog on the approaches I went through to implement this.
The rough iterations that happened during the development are documented in the approach folder. It contains both the AST manipulation method, and the "truly cursed" method.
The "old way" usage
The first version (as shown in the original tweet) is also present in the repository, for archival purposes.
Note that this only really works in a REPL. To start it, run cursedfor.py in the terminal. It's a single file, you can get it by just downloading the one file if you want to.
>>> with _for(i := 0, i < 10, i += 2):
... print(i)
0
2
4
6
8
Help, something is broken!
You can use the cursed-for-decode
command to figure out what code is being
generated by the module:
$ cat x.py
for (i = 1; i < 100; i += 1):
print(i)
$ cursed-for-decode x.py
i = 1
while i < 100:
print(i)
i += 1
If the generated code seems wrong, file a bug report with the code snippet.