Ir al contenido principal

# BPython Lives!!!

In Jan­uary, I sug­gest­ed it would be triv­ial to write a pre­proces­sor that would ac­cept a ver­sion of python which de­lim­it­ed blocks with braces in­stead of in­den­ta­tion.

Ok, al­most, I sug­gest­ed #{ and #} as de­lim­iter­s.

Well, I had a few min­utes free to­day, and here it is, a func­tion­al BPython->Python com­pil­er, so to speak.

Here's the kind of im­put it takes (no­tice how it's not in­dent­ed at al­l:

```def factorial(n):
#{
if n==1:
#{
return 1
#}
else:
#{
return n*factorial(n-1)
#}
#}

for x in range(1,10):
#{
print x,"!=",factorial(x)
#}```

And it pro­duces this (I am not hap­py with the in­dent­ing of the com­ments, but who cares):

```def factorial(n):
#{
if n==1:
#{
return 1
#}
else:
#{
return n*factorial(n-1)
#}
#}

for x in range(1,10):
#{
print x,"!=",factorial(x)
#}
```

As you can see, this is both a le­gal Python and a le­gal BPython pro­gram ;-)

It has some prob­lem­s, like not work­ing when you use a line like this:

`#{ x=1`

But hey, it is python with braces.

Here's the code. I pre­dict­ed 30 lines. It's 34. And it's 99% a ripoff of Ka Ping Yee's re­gur­gi­tate.py which you can find all around the we­b.

```#!/usr/bin/env python
import tokenize, sys
program = []
lastrow, lastcol = 1, 0
lastline = ''
indlevel=0
def rebuild(type, token, (startrow, startcol), (endrow, endcol), line):
global lastrow, lastcol, lastline, program,indlevel
if type==52 and token.startswith ("#{"):
type=5
indlevel+=1
if type==52 and token.startswith ("#}"):
type=6
indlevel-=1
line="  "*indlevel+line.lstrip()
startcol+=indlevel*2
endcol+=indlevel*2
# Deal with the bits between tokens.
if lastrow == startrow == endrow:            # ordinary token
program.append(line[lastcol:startcol])
elif lastrow != startrow:                    # backslash continuation
program.append(lastline[lastcol:] + line[:startcol])
elif startrow != endrow:                     # multi-line string
program.append(lastline[lastcol:startcol])
# Append the token itself.
program.append(token)
# Save some information for the next time around.
if token and token[-1] == '\n':
lastrow, lastcol = endrow+1, 0           # start on next line
else:
lastrow, lastcol = endrow, endcol        # remember last position
lastline = line                              # remember last line
for piece in program: sys.stdout.write(piece)
```

So, all of you who dis­like python be­cause of the lack of braces and the sig­nif­i­cant whites­pace:

BPython has no sig­nif­i­cant whites­pace, and braces are manda­to­ry.

En­joy cod­ing!

/ 2006-04-02 09:37:

It would be pretty straightforward to just build this functionality into Iron Python - with the C# source being readily available. That way you could get your brace delimited Python up and running on machines with the .NET Framework (or Mono) without a pre-processor.

/ 2006-04-02 14:36:

Maybe I didn't make it clear enough that I think brace delimited python sucks ;-)