Sunday, February 25, 2007

Writing Domain Specific Languages with Python

  • The process of writing DSL is the same in all languages.
    • You write an ideal spec.
    • Then, you try to fit the spec so that it's kind of valid syntax for the language you use.
  • An example of ideal domain language (well, maybe not so ideal, but quite good):

test '/Login':
GetReq(uname = 'a_user',
password = '')
expect_tmpl: 'login.tmpl'
expect_tmpl_has: 'errorMsg'
expect_tmpl_data: { 'uname':'a_user',
'missing_fields' : ['Password']}
expect_session_lacks: 'uid'
  • Now the same but as a valid Python syntax:

test_serv('/Login',
GetReq(uname = 'a_user',
password = ''),
expect_tmpl = 'login.tmpl',
expect_tmpl_has = 'errorMsg',
expect_tmpl_data = { 'uname':'a_user',
'missing_fields' : ['Password']},
expect_session_lacks = 'uid')

  • Useful tricks inclue:
    • keyword args (expect_tmpl_data=...)
    • unbounded arg lists (*args)
    • operator overloading __add__(self, other_form)
    • reflection via hasattr, getattr, vars and friends
  • Thanks to Dan Milstein for his talk at PyCon about Little Languages in Python.

No comments: