PyCon: Embedding Little Languages in Python

Little languages embedded in Python can improve the readability of code by allowing the coder to specify what he's trying to do (declarative) rather than how to do it (imperative). First you dream up a syntax for what you're trying to convey by typing some pretend code, and then you try to get Python to conform to something similar to your ideal syntax. The author did not cover using a parser, but instead misused (in a good way) Python syntax. He suggested the following tricks:
  • Make use of function parameter lists, including keywords, *args, and **kargs.
  • Use Python classes to represent states. Use methods for transitions.
  • Use reflection tricks.
  • Put domain specific syntax in docstrings.
  • Use operator overloading by doing things like implementing the __add__ method.
All in all, his tricks were all pretty simple. I'm sure all the RoR coders out there are yawning. However, it was a fun talk anyway. Unfortunately, I got so carried away, I missed two talks while talking with some guy about parsers and various other things.


Anonymous said…
Hi, Could you please give an example of point two:
Use python objects for state and methods for transitions.

jjinux said…
The slides are here:

Blogger will probably trample the indentation, but here's the example in the slides:

class Unassigned(TaskState):
def to_Assigned(self, task):
task.email_assignee("Task has been assigned to you")

class Assigned(TaskState):
def to_Declined(self, task):
task.email_manager("Task has been declined")

def to_Assigned(self, task):
task.email_old_assignee, 'Task has been reassigned')
task.email_new_assignee, 'Task has been assigned')

def to_Accepted(self, task):
task.email_manager("Task has been accepted")