Hacking The Python For Loop

In the early days of C, you’d at times see someone — possibly a previous Pascal programmer — generate some thing like this:

#determine Begin
#determine End

This would normally initiate problems about abusing the preprocessor and typically staying anti-C. Absolutely no contemporary language would allow these kinds of factors, correct? Most likely not. Take into consideration [Tushar Sadhwani] who required to produce a basic C-model for loop inside of Python. He did it, and the journey is most likely far more intriguing than the end result.

1st, you just cannot just transport straight C for loops into Python. There has to be some concession to Python syntax. The preliminary attempt was clever but not clever enough. On the other hand, the disassembly of the Python code was telling. The next try, however, was notably appealing.

That endeavor applied an odd attribute to analyze the interpreter’s tree construction for the code and then modify it. This is kind of like a quite agonizing C preprocessor but far more strong. That variation performs although it is very convoluted.

Ironically, [Tushar] then established up a third endeavor following viewing code that attempts to swap Python indentation with braces using a codec. In Python-communicate, a codec lets you transform various textual content encodings. On the other hand, you can do other matters than textual content encoding conversion. This is closest in spirit to the C preprocessor system. You can wade through the resource code ahead of processing and make whichever improvements you see in shape.

Is any of this definitely valuable? In all probability not as it is. But you hardly ever know when you might have to have to do some thing unique and a person of these tactics could help you save the day. You most likely couldn’t get absent with some of this on MicroPython, of course. Your mileage could change depending on exactly where you locate your Python running — like the World-wide-web.