` Code Snippets - CurlyPy `

CurlyPy

This short python snippet lets you use curly braces instead of indentation in your python scripts, by implementing a preprocessor which converts from curly brackets/semi-colon delimited syntax into valid (indented) python.

Use curlypy.py like this:

		python curlypy.py < before.py > after.py
		
before.py
class klass {

	def __init__(self,x) {
		self.x = x;
	}

	def method1(self) {
		print self.x;
	}

/*
	def method2(self) {
		print self.y;
	}
*/
}

def fun(x) {
	return x*x;
}

print fun(20);
k = klass(10);
k.method1();
after.py
class klass:
    
    def __init__(self,x):
        self.x = x
    
    
    def method1(self):
        print self.x
    
    


def fun(x):
    return x*x


print fun(20)
k = klass(10)
k.method1()
The code for curylpy.py is listed below. Note that curlypy also handles C-style comments /* like this */ (these are removed from the generated python).

curlypy.py
# curlypy.py - preprocessor for curly bracket styled python
# Copyright (c) 2008 Niall McCarroll  
# Distributed under the MIT/X11 License (http://www.mccarroll.net/snippets/license.txt)

import sys
inlines = map(lambda x:x.strip(),sys.stdin.read().split("\n"))
indent = ''
indentstr = '    '
incomment = False

for line in inlines:
	if line.startswith("/*"): incomment = True
	if line.endswith("*/"): incomment = False; continue
	if incomment: continue
	openblock = False
	if line.endswith("}"):
		indent = indent[:-len(indentstr)]
		line = line[:-1]
	elif line.endswith("{"):
		openblock = True
		line = line[:-1].rstrip() + ':'
	print indent + line.rstrip(";")
	if openblock:
		indent += indentstr

 

Leave a comment

Anti-Spam Check
Comment