In response to Wai's comment, here is one interesting solution that I found. First of all, to explain again what it does, suppose you have the following code:
definitions = Structure() definitions.add_definition('f[x]', 'x*2') definitions.add_definition('f[z]', 'some_function(z)') definitions.add_definition('g.i', 'some_object[i].method(param=value)')
where adding definitions involves parsing the left side and the right side and doing other ugly things. Now one (not necessarily good, but certainly funny) approach would allow writing the code above as follows:
@my_dsl def definitions(): f[x] = x*2 f[z] = some_function(z) gi = some_object[i].method(param=value)
and Python does most of the parsing under the hood. The idea is based on a simple statement exec <code> in <environment> mentioned by Jan, with one hacker addition. Namely, the byte code of the function should be slightly changed, and all operations with local variable access (LOAD_FAST) switched to variable access from the environment (LOAD_NAME).
This is easier than explained: http://fouryears.eu/wp-content/uploads/pydsl/
There are various tricks you can do to make them practical. For example, in the code provided by the link above, you cannot use the built-in functions and language constructs, for example, for loops and if statements in the @my_dsl function. However, you can make them work by adding more behavior to the Env class.
Update Here is a slightly more detailed explanation of the same.
source share