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.
Comments
Use python objects for state and methods for transitions.
Thanks
Andrew
http://us.pycon.org/common/talkdata/PyCon2007/048/little-langs-correct.zip
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")