Created
September 28, 2011 23:34
-
-
Save mattjmorrison/1249582 to your computer and use it in GitHub Desktop.
Create a DSL in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> python run_dsl.py | |
Greater | |
ZERO! | |
Less |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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