# 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