New to Python - block grouping (spaces)

BartC bc at freeuk.com
Thu Apr 16 12:51:32 CEST 2015


On 16/04/2015 06:49, Steven D'Aprano wrote:
> On Thursday 16 April 2015 14:07, Blake McBride wrote:

>> Is there a utility that will allow me to write Python-like code that
>> includes some block delimiter that I can see, that converts the code into
>> runnable Python code?  If so, where can I find it?

> No more bugs from accidentally forgetting to use optional braces!

You get bugs instead from mistakenly using the wrong indentation or 
losing the correct indentation (accidentally pressing the wrong key for 
example).

> If you find such a preprocessor, or write your own, feel free to use it. But
> you won't get any respect from experienced Python programmers: we use Python
> in part to get away from braces, we're not chomping at the bit to put them
> back in.
>
> I'm aware that Coffeescript provides a brace-free wrapper around Javascript;
> I'm not aware of any wrapper that *adds* braces to a language without them.
> I suspect such a thing would be of limited use and even less popularity. But
> feel free to try developing one, I could be wrong!

I used a wrapper a couple of years ago that allowed me to write in my 
own Algol68-style syntax and produce Python as output. A short example 
might have this as input:

proc start=
   to 10 do
     println "Hello World"
   od
end

and produced:

import sys
import math
import copy

def start():
     _tmp1=10
     while _tmp1>0:
         sys.stdout.write(str("Hello World"))
         sys.stdout.write("\n")
         _tmp1=_tmp1-1

start()

(It actually worked quite well, for small programs, and I managed to get 
the same input converted to Lisp and Lua too. Also, for very simple 
programs, to C, but this requires static type declarations which are 
ignored for Python output.

However the main problem was that Python was too semantically different 
from the way I normally used the input language, and now that language 
is self-contained and does its own thing.)

This wrapper took the form of a proper parser for the input, producing 
an abstract syntax tree, which was then written out in the output syntax 
of choice.

Where the input is already nearly Python, then it can much simpler, but 
it can't do so much checking. If there is a 1:1 correspondence between 
line numbers of input and output, then it makes it easier to match any 
Python errors with the original not-quite-Python source code.

I've used this approach to add Algol-68 block delimiters (and change a 
few other things I found annoying) to C code.

-- 
Bartc



More information about the Python-list mailing list