Skip to content

Instantly share code, notes, and snippets.

@mattjmorrison
Created September 28, 2011 23:34
Show Gist options
  • Save mattjmorrison/1249582 to your computer and use it in GitHub Desktop.
Save mattjmorrison/1249582 to your computer and use it in GitHub Desktop.
Create a DSL in Python
import types
import re
buffer_regex = re.compile(r'^([\t\s]*)\w')
def dedent(code):
replace_chunk = ''
for line in code.split('\n'):
matches = buffer_regex.search(line)
if matches:
replace_chunk = matches.group(1)
break
dedented_lines = []
for line in code.split('\n'):
dedented_lines.append(line.replace(replace_chunk, ''))
return '\n'.join(dedented_lines)
def do(code):
return compile(dedent(code), __file__, 'exec')
def it(name, code, data):
for arg in data:
types.FunctionType(code, arg, name)()
def data(*args):
for arg in args:
yield arg
> python run_dsl.py
Greater
ZERO!
Less
#!/usr/bin/python
from dsl import it, do, data
if __name__ == '__main__':
it('matthew', do("""
if x > 0:
print "Greater"
elif x < 0:
print "Less"
else:
print "ZERO!"
"""), data(
dict(x=1),
dict(x=0),
dict(x=-1),
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment